How to sort an array of associative arrays by value of a given key in PHP?
Given this array:
$inventory = array(
array("type"=>"fruit", "price"=>3.50),
array("type"=>"milk", "price"=>2.90),
array("type"=>"pork", "price"=>5.43),
);
I would like to sort $inventory
's elements by price to get:
$inventory = array(
array("type"=>"pork", "price"=>5.43),
array("type"=>"fruit", "price"=>3.50),
array("type"=>"milk", "price"=>2.90),
);
How can I do this?
php sorting
add a comment |
Given this array:
$inventory = array(
array("type"=>"fruit", "price"=>3.50),
array("type"=>"milk", "price"=>2.90),
array("type"=>"pork", "price"=>5.43),
);
I would like to sort $inventory
's elements by price to get:
$inventory = array(
array("type"=>"pork", "price"=>5.43),
array("type"=>"fruit", "price"=>3.50),
array("type"=>"milk", "price"=>2.90),
);
How can I do this?
php sorting
3
possible duplicate of How do I sort a multidimensional array in php
– Jon
Jul 26 '13 at 9:33
If you are using Eloquent ORM, here's a nice answer.
– Pathros
Jan 20 '16 at 20:02
add a comment |
Given this array:
$inventory = array(
array("type"=>"fruit", "price"=>3.50),
array("type"=>"milk", "price"=>2.90),
array("type"=>"pork", "price"=>5.43),
);
I would like to sort $inventory
's elements by price to get:
$inventory = array(
array("type"=>"pork", "price"=>5.43),
array("type"=>"fruit", "price"=>3.50),
array("type"=>"milk", "price"=>2.90),
);
How can I do this?
php sorting
Given this array:
$inventory = array(
array("type"=>"fruit", "price"=>3.50),
array("type"=>"milk", "price"=>2.90),
array("type"=>"pork", "price"=>5.43),
);
I would like to sort $inventory
's elements by price to get:
$inventory = array(
array("type"=>"pork", "price"=>5.43),
array("type"=>"fruit", "price"=>3.50),
array("type"=>"milk", "price"=>2.90),
);
How can I do this?
php sorting
php sorting
edited May 2 '15 at 23:10


Mark Amery
63.2k31253302
63.2k31253302
asked Oct 20 '09 at 22:47
MattMatt
8,5832264103
8,5832264103
3
possible duplicate of How do I sort a multidimensional array in php
– Jon
Jul 26 '13 at 9:33
If you are using Eloquent ORM, here's a nice answer.
– Pathros
Jan 20 '16 at 20:02
add a comment |
3
possible duplicate of How do I sort a multidimensional array in php
– Jon
Jul 26 '13 at 9:33
If you are using Eloquent ORM, here's a nice answer.
– Pathros
Jan 20 '16 at 20:02
3
3
possible duplicate of How do I sort a multidimensional array in php
– Jon
Jul 26 '13 at 9:33
possible duplicate of How do I sort a multidimensional array in php
– Jon
Jul 26 '13 at 9:33
If you are using Eloquent ORM, here's a nice answer.
– Pathros
Jan 20 '16 at 20:02
If you are using Eloquent ORM, here's a nice answer.
– Pathros
Jan 20 '16 at 20:02
add a comment |
17 Answers
17
active
oldest
votes
You are right, the function you're looking for is array_multisort()
.
Here's an example taken straight from the manual and adapted to your case:
$price = array();
foreach ($inventory as $key => $row)
{
$price[$key] = $row['price'];
}
array_multisort($price, SORT_DESC, $inventory);
5
Though this is definitely more expensive than the alternatives.
– Matt
Oct 22 '09 at 0:39
3
More expensive? That's weird, on my machine (running PHP 5.3.1-dev) array_multisort() is a few percent faster on small arrays and up to 100 times faster on big arrays (100+ elements)
– Josh Davis
Oct 22 '09 at 2:49
1
Is there a way to make it work with numeric keys?
– Dennis
Jan 4 '12 at 12:30
3
It shouldn't require any change to work with numeric keys. If you're hitting a bug or weird behaviour related to numeric keys, post it as a new question.
– Josh Davis
Jan 5 '12 at 0:22
3
array_multisort has a big problem: it doesn't maintain the original key.
– machineaddict
Sep 27 '13 at 7:04
|
show 6 more comments
PHP 7+
As of PHP 7, this can be done concisely using usort
with an anonymous function that uses the spaceship operator to compare elements.
You can do an ascending sort like this:
usort($inventory, function ($item1, $item2) {
return $item1['price'] <=> $item2['price'];
});
Or a descending sort like this:
usort($inventory, function ($item1, $item2) {
return $item2['price'] <=> $item1['price'];
});
To understand how this works, note that usort
takes a user-provided comparison function that must behave as follows (from the docs):
The comparison function must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second.
And note also that <=>
, the spaceship operator,
returns 0 if both operands are equal, 1 if the left is greater, and -1 if the right is greater
which is exactly what usort
needs. In fact, almost the entire justification given for adding <=>
to the language in https://wiki.php.net/rfc/combined-comparison-operator is that it
makes writing ordering callbacks for use with
usort()
easier
PHP 5.3+
PHP 5.3 introduced anonymous functions, but doesn't yet have the spaceship operator. We can still use usort
to sort our array, but it's a little more verbose and harder to understand:
usort($inventory, function ($item1, $item2) {
if ($item1['price'] == $item2['price']) return 0;
return $item1['price'] < $item2['price'] ? -1 : 1;
});
Note that although it's fairly common for comparators dealing with integer values to just return the difference of the values, like $item2['price'] - $item1['price']
, we can't safely do that in this case. This is because the prices are floating point numbers in the question asker's example, but the comparison function we pass to usort
has to return integers for usort
to work properly:
Returning non-integer values from the comparison function, such as float, will result in an internal cast to integer of the callback's return value. So values such as 0.99 and 0.1 will both be cast to an integer value of 0, which will compare such values as equal.
This is an important trap to bear in mind when using usort
in PHP 5.x! My original version of this answer made this mistake and yet I accrued ten upvotes over thousands of views apparently without anybody noticing the serious bug. The ease with which lackwits like me can screw up comparator functions is precisely the reason that the easier-to-use spaceship operator was added to the language in PHP 7.
6
Sorry, but this approach deletes the string keys from associative arrays. "uasort" function should be used, instead.
– Matteo-SoftNet
Mar 26 '14 at 11:54
7
@DotMat Interesting - I didn't know aboutuasort
. After looking at the docs, though, this answer is still correct in this case. In the OP's example, the array to be sorted has sequential numeric indexes rather than string indexes, sousort
is more appropriate. Usinguasort
on a sequentially-indexed array will result in a sorted array which is not ordered by its numeric indexes, such that the first element seen in aforeach
loop is not$your_array[0]
, which is unlikely to be desirable behaviour.
– Mark Amery
Mar 26 '14 at 12:47
add a comment |
While others have correctly suggested the use of array_multisort()
, for some reason no answer seems to acknowledge the existence of array_column()
, which can greatly simplify the solution. So my suggestion would be:
array_multisort(array_column($inventory, 'price'), SORT_DESC, $inventory);
1
For some reason I was not able to make it work with strings having lower/upper letters. Even using the SORT_FLAG_CASE. The following worked for string comparision for me: array_multisort( array_map(strtolower, array_column($ipr_projects, 'Name')), SORT_ASC, $ipr_projects);
– Pabamato
Apr 19 '18 at 22:36
6
This is the most elegant answer. Should be rated much higher!
– Armin Hierstetter
Aug 1 '18 at 9:44
1
shortest and easiest one, accepted one in my opinion
– StudioX
Dec 15 '18 at 9:38
add a comment |
Since your array elements are arrays themselves with string keys, your best bet is to define a custom comparison function. It's pretty quick and easy to do. Try this:
function invenDescSort($item1,$item2)
{
if ($item1['price'] == $item2['price']) return 0;
return ($item1['price'] < $item2['price']) ? 1 : -1;
}
usort($inventory,'invenDescSort');
print_r($inventory);
Produces the following:
Array
(
[0] => Array
(
[type] => pork
[price] => 5.43
)
[1] => Array
(
[type] => fruit
[price] => 3.5
)
[2] => Array
(
[type] => milk
[price] => 2.9
)
)
3
Combining with some of the other comments here (uasort and inline anonymous functions), you get this one-liner:uasort( $inventory, function ($a, $b) { if ( $a==$b ) return 0; else return ($a > $b) ? -1 : 1; });
– Alan Porter
May 1 '14 at 12:44
@AlanPorterusort
seems more appropriate thanuasort
for sorting an array with sequential numeric keys. Ending up with an array where the first element is at index1
and the second element is at index0
is weird behavior and a sure trap for people who aren't familiar with the details of PHP's arrays;usort
gives you the output you'd intuitively expect.
– Mark Amery
May 2 '15 at 23:13
add a comment |
I ended on this:
function sort_array_of_array(&$array, $subfield)
{
$sortarray = array();
foreach ($array as $key => $row)
{
$sortarray[$key] = $row[$subfield];
}
array_multisort($sortarray, SORT_ASC, $array);
}
Just call the function, passing the array and the name of the field of the second level array.
Like:
sort_array_of_array($inventory, 'price');
1
Ha! I just make pretty-much exactly the same thing and was gonna post but saw yours... upvoted.
– Rob Evans
Apr 5 '14 at 21:12
1
Downvoting because this is exactly the same solution that Josh Davis posted years earlier.
– Mark Amery
Oct 22 '15 at 21:44
Disagree... I didn't say it's a different solution, I just said that I ended with this solution and give a full working function.
– Danielzt
Jan 24 '17 at 18:30
1
@MarkAmery I prefer answers contained in functions. It encourages copy pasters to use functions and hopefully write less spaghetti code.
– Goose
Jun 1 '17 at 23:53
add a comment |
You can use usort
with anonymous function, e.g.
usort($inventory, function ($a, $b) { return strnatcmp($a['price'], $b['price']); });
Versions PHP 5 >= 5.5.0, PHP 7 for those of you like me that really wanted this to work for them..
– Matt P
Feb 21 '18 at 22:43
add a comment |
$inventory =
array(array("type"=>"fruit", "price"=>3.50),
array("type"=>"milk", "price"=>2.90),
array("type"=>"pork", "price"=>5.43),
);
function pricesort($a, $b) {
$a = $a['price'];
$b = $b['price'];
if ($a == $b)
return 0;
return ($a > $b) ? -1 : 1;
}
usort($inventory, "pricesort");
// uksort($inventory, "pricesort");
print("first: ".$inventory[0]['type']."nn");
// for usort(): prints milk (item with lowest price)
// for uksort(): prints fruit (item with key 0 in the original $inventory)
// foreach prints the same for usort and uksort.
foreach($inventory as $i){
print($i['type'].": ".$i['price']."n");
}
outputs:
first: pork
pork: 5.43
fruit: 3.5
milk: 2.9
add a comment |
Was tested on 100 000 records:
Time in seconds(calculated by funciton microtime).
Only for unique values on sorting key positions.
Solution of function of @Josh Davis:
Spended time: 1.5768740177155
Mine solution:
Spended time: 0.094044923782349
Solution:
function SortByKeyValue($data, $sortKey, $sort_flags=SORT_ASC)
{
if (empty($data) or empty($sortKey)) return $data;
$ordered = array();
foreach ($data as $key => $value)
$ordered[$value[$sortKey]] = $value;
ksort($ordered, $sort_flags);
return array_values($ordered); *// array_values() added for identical result with multisort*
}
7
The requirement for unique sort keys is sort of a deal breaker, though. If you have unique sort values that can be keys, it begs the question: why not simply construct the array with those keys to begin with? In the OP's scenario, it is difficult to imagine that two items with the same price would be impossible. That in mind, using this solution would cause items from the array to mysteriously and silently disappear from the sorted result set.
– Chris Baker
Dec 4 '13 at 20:41
Thanks. This works for me
– Mahesh
Feb 19 '14 at 10:54
@Chris Baker, you are right. This works only for unique values. But this solution works very fast, so speed was the reason of make and use it. At the moment may be it is not actual, need to test it with PHP 7.1.x.
– Nefelim
Jan 3 '17 at 9:04
add a comment |
From Sort an array of associative arrays by value of given key in php:
uasort (http://php.net/uasort) allows you to sort an array by your own defined function. In your case, that's simple:
$array = array(
array('price'=>'1000.50','product'=>'test1'),
array('price'=>'8800.50','product'=>'test2'),
array('price'=>'200.0','product'=>'test3')
);
function cmp($a, $b) {
return $a['price'] > $b['price'];
}
uasort($array, "cmp");
1
This answer turned up in the low quality review queue, presumably because you don't provide any explanation of the code. If this code answers the question, consider adding adding some text explaining the code in your answer. This way, you are far more likely to get more upvotes — and help the questioner learn something new.
– lmo
Aug 30 '16 at 23:00
1
hmpf. this is the best answer tho.
– commonpike
Apr 11 '18 at 21:01
add a comment |
You might try to define your own comparison function and then use usort.
Yes. I'll do that if I can't find a solution. I'm pretty sure there are some weird parameters you can add to one of the sorts to accomplish this. Thanks for your thoughts though!
– Matt
Oct 20 '09 at 22:58
add a comment |
This function is re-usable:
function usortarr(&$array, $key, $callback = 'strnatcasecmp') {
uasort($array, function($a, $b) use($key, $callback) {
return call_user_func($callback, $a[$key], $b[$key]);
});
}
It works well on string values by default, but you'll have to sub the callback for a number comparison function if all your values are numbers.
add a comment |
//Just in one line custom function
function cmp($a, $b)
{
return (float) $a['price'] < (float)$b['price'];
}
@uasort($inventory, "cmp");
print_r($inventory);
//result
Array
(
[2] => Array
(
[type] => pork
[price] => 5.43
)
[0] => Array
(
[type] => fruit
[price] => 3.5
)
[1] => Array
(
[type] => milk
[price] => 2.9
)
)
add a comment |
Here is a method that I found long ago and cleaned up a bit. This works great, and can be quickly changed to accept objects as well.
/**
* A method for sorting arrays by a certain key:value.
* SortByKey is the key you wish to sort by
* Direction can be ASC or DESC.
*
* @param $array
* @param $sortByKey
* @param $sortDirection
* @return array
*/
private function sortArray($array, $sortByKey, $sortDirection) {
$sortArray = array();
$tempArray = array();
foreach ( $array as $key => $value ) {
$tempArray = strtolower( $value[ $sortByKey ] );
}
if($sortDirection=='ASC'){ asort($tempArray ); }
else{ arsort($tempArray ); }
foreach ( $tempArray as $key => $temp ){
$sortArray = $array[ $key ];
}
return $sortArray;
}
to change the method to sort objects simply change the following line:
$tempArray = strtolower( $value[ $sortByKey ] );
to
$tempArray = strtolower( $value->$sortByKey );
To run the method simply do
sortArray($inventory,'price','ASC');
add a comment |
$arr1 = array(
array('id'=>1,'name'=>'aA','cat'=>'cc'),
array('id'=>2,'name'=>'aa','cat'=>'dd'),
array('id'=>3,'name'=>'bb','cat'=>'cc'),
array('id'=>4,'name'=>'bb','cat'=>'dd')
);
$result1 = array_msort($arr1, array('name'=>SORT_DESC);
$result2 = array_msort($arr1, array('cat'=>SORT_ASC);
$result3 = array_msort($arr1, array('name'=>SORT_DESC, 'cat'=>SORT_ASC));
function array_msort($array, $cols)
{
$colarr = array();
foreach ($cols as $col => $order) {
$colarr[$col] = array();
foreach ($array as $k => $row) { $colarr[$col]['_'.$k] = strtolower($row[$col]); }
}
$eval = 'array_multisort(';
foreach ($cols as $col => $order) {
$eval .= '$colarr[''.$col.''],'.$order.',';
}
$eval = substr($eval,0,-1).');';
eval($eval);
$ret = array();
foreach ($colarr as $col => $arr) {
foreach ($arr as $k => $v) {
$k = substr($k,1);
if (!isset($ret[$k])) $ret[$k] = $array[$k];
$ret[$k][$col] = $array[$k][$col];
}
}
return $ret;
}
While this code snippet may solve the question, including an explanation really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion. Please also try not to crowd your code with explanatory comments, as this reduces the readability of both the code and the explanations!
– FrankerZ
Aug 30 '16 at 20:35
add a comment |
Complete Dynamic Function
I jumped here for associative array sorting and found this amazing function on http://php.net/manual/en/function.sort.php. This function is very dynamic that sort in ascending and descending order with specified key.
Simple function to sort an array by a specific key. Maintains index association
<?php
function array_sort($array, $on, $order=SORT_ASC)
{
$new_array = array();
$sortable_array = array();
if (count($array) > 0) {
foreach ($array as $k => $v) {
if (is_array($v)) {
foreach ($v as $k2 => $v2) {
if ($k2 == $on) {
$sortable_array[$k] = $v2;
}
}
} else {
$sortable_array[$k] = $v;
}
}
switch ($order) {
case SORT_ASC:
asort($sortable_array);
break;
case SORT_DESC:
arsort($sortable_array);
break;
}
foreach ($sortable_array as $k => $v) {
$new_array[$k] = $array[$k];
}
}
return $new_array;
}
$people = array(
12345 => array(
'id' => 12345,
'first_name' => 'Joe',
'surname' => 'Bloggs',
'age' => 23,
'sex' => 'm'
),
12346 => array(
'id' => 12346,
'first_name' => 'Adam',
'surname' => 'Smith',
'age' => 18,
'sex' => 'm'
),
12347 => array(
'id' => 12347,
'first_name' => 'Amy',
'surname' => 'Jones',
'age' => 21,
'sex' => 'f'
)
);
print_r(array_sort($people, 'age', SORT_DESC)); // Sort by oldest first
print_r(array_sort($people, 'surname', SORT_ASC)); // Sort by surname
add a comment |
<?php
$inventory = array(
array("type"=>"fruit", "price"=>3.50),
array("type"=>"milk", "price"=>2.90),
array("type"=>"pork", "price"=>5.43),
);
function myfunc($a,$b){
return strnatcmp($a['price'],$b['price']);
}
$result=usort ($inventory,"myfunc");?>
<pre><?php print_r(array_reverse($inventory)); ?></pre>
the simple solution :)
the output is,
Array
(
[0] => Array
(
[type] => pork
[price] => 5.43
)
[1] => Array
(
[type] => fruit
[price] => 3.5
)
[2] => Array
(
[type] => milk
[price] => 2.9
)
)
This answer turned up in the low quality review queue, presumably because you don't provide any explanation of the code. If this code answers the question, consider adding adding some text explaining the code in your answer. This way, you are far more likely to get more upvotes — and help the questioner learn something new.
– lmo
Aug 30 '16 at 23:02
add a comment |
try this:
asort($array_to_sort, SORT_NUMERIC);
for reference see this:
http://php.net/manual/en/function.asort.php
see various sort flags here:
http://www.php.net/manual/en/function.sort.php
this won't work for multidimensional arrays, but just helped me out for another problem, thanks :)
– schellmax
Feb 3 '12 at 12:13
4
This can't be used to sort a list of dictionaries by a particular dictionary key, and hence doesn't answer the question posed.
– Mark Amery
Oct 18 '13 at 16:19
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f1597736%2fhow-to-sort-an-array-of-associative-arrays-by-value-of-a-given-key-in-php%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
17 Answers
17
active
oldest
votes
17 Answers
17
active
oldest
votes
active
oldest
votes
active
oldest
votes
You are right, the function you're looking for is array_multisort()
.
Here's an example taken straight from the manual and adapted to your case:
$price = array();
foreach ($inventory as $key => $row)
{
$price[$key] = $row['price'];
}
array_multisort($price, SORT_DESC, $inventory);
5
Though this is definitely more expensive than the alternatives.
– Matt
Oct 22 '09 at 0:39
3
More expensive? That's weird, on my machine (running PHP 5.3.1-dev) array_multisort() is a few percent faster on small arrays and up to 100 times faster on big arrays (100+ elements)
– Josh Davis
Oct 22 '09 at 2:49
1
Is there a way to make it work with numeric keys?
– Dennis
Jan 4 '12 at 12:30
3
It shouldn't require any change to work with numeric keys. If you're hitting a bug or weird behaviour related to numeric keys, post it as a new question.
– Josh Davis
Jan 5 '12 at 0:22
3
array_multisort has a big problem: it doesn't maintain the original key.
– machineaddict
Sep 27 '13 at 7:04
|
show 6 more comments
You are right, the function you're looking for is array_multisort()
.
Here's an example taken straight from the manual and adapted to your case:
$price = array();
foreach ($inventory as $key => $row)
{
$price[$key] = $row['price'];
}
array_multisort($price, SORT_DESC, $inventory);
5
Though this is definitely more expensive than the alternatives.
– Matt
Oct 22 '09 at 0:39
3
More expensive? That's weird, on my machine (running PHP 5.3.1-dev) array_multisort() is a few percent faster on small arrays and up to 100 times faster on big arrays (100+ elements)
– Josh Davis
Oct 22 '09 at 2:49
1
Is there a way to make it work with numeric keys?
– Dennis
Jan 4 '12 at 12:30
3
It shouldn't require any change to work with numeric keys. If you're hitting a bug or weird behaviour related to numeric keys, post it as a new question.
– Josh Davis
Jan 5 '12 at 0:22
3
array_multisort has a big problem: it doesn't maintain the original key.
– machineaddict
Sep 27 '13 at 7:04
|
show 6 more comments
You are right, the function you're looking for is array_multisort()
.
Here's an example taken straight from the manual and adapted to your case:
$price = array();
foreach ($inventory as $key => $row)
{
$price[$key] = $row['price'];
}
array_multisort($price, SORT_DESC, $inventory);
You are right, the function you're looking for is array_multisort()
.
Here's an example taken straight from the manual and adapted to your case:
$price = array();
foreach ($inventory as $key => $row)
{
$price[$key] = $row['price'];
}
array_multisort($price, SORT_DESC, $inventory);
edited Nov 16 '18 at 4:15


Jeff Puckett
15k756108
15k756108
answered Oct 21 '09 at 2:06
Josh DavisJosh Davis
22.8k54365
22.8k54365
5
Though this is definitely more expensive than the alternatives.
– Matt
Oct 22 '09 at 0:39
3
More expensive? That's weird, on my machine (running PHP 5.3.1-dev) array_multisort() is a few percent faster on small arrays and up to 100 times faster on big arrays (100+ elements)
– Josh Davis
Oct 22 '09 at 2:49
1
Is there a way to make it work with numeric keys?
– Dennis
Jan 4 '12 at 12:30
3
It shouldn't require any change to work with numeric keys. If you're hitting a bug or weird behaviour related to numeric keys, post it as a new question.
– Josh Davis
Jan 5 '12 at 0:22
3
array_multisort has a big problem: it doesn't maintain the original key.
– machineaddict
Sep 27 '13 at 7:04
|
show 6 more comments
5
Though this is definitely more expensive than the alternatives.
– Matt
Oct 22 '09 at 0:39
3
More expensive? That's weird, on my machine (running PHP 5.3.1-dev) array_multisort() is a few percent faster on small arrays and up to 100 times faster on big arrays (100+ elements)
– Josh Davis
Oct 22 '09 at 2:49
1
Is there a way to make it work with numeric keys?
– Dennis
Jan 4 '12 at 12:30
3
It shouldn't require any change to work with numeric keys. If you're hitting a bug or weird behaviour related to numeric keys, post it as a new question.
– Josh Davis
Jan 5 '12 at 0:22
3
array_multisort has a big problem: it doesn't maintain the original key.
– machineaddict
Sep 27 '13 at 7:04
5
5
Though this is definitely more expensive than the alternatives.
– Matt
Oct 22 '09 at 0:39
Though this is definitely more expensive than the alternatives.
– Matt
Oct 22 '09 at 0:39
3
3
More expensive? That's weird, on my machine (running PHP 5.3.1-dev) array_multisort() is a few percent faster on small arrays and up to 100 times faster on big arrays (100+ elements)
– Josh Davis
Oct 22 '09 at 2:49
More expensive? That's weird, on my machine (running PHP 5.3.1-dev) array_multisort() is a few percent faster on small arrays and up to 100 times faster on big arrays (100+ elements)
– Josh Davis
Oct 22 '09 at 2:49
1
1
Is there a way to make it work with numeric keys?
– Dennis
Jan 4 '12 at 12:30
Is there a way to make it work with numeric keys?
– Dennis
Jan 4 '12 at 12:30
3
3
It shouldn't require any change to work with numeric keys. If you're hitting a bug or weird behaviour related to numeric keys, post it as a new question.
– Josh Davis
Jan 5 '12 at 0:22
It shouldn't require any change to work with numeric keys. If you're hitting a bug or weird behaviour related to numeric keys, post it as a new question.
– Josh Davis
Jan 5 '12 at 0:22
3
3
array_multisort has a big problem: it doesn't maintain the original key.
– machineaddict
Sep 27 '13 at 7:04
array_multisort has a big problem: it doesn't maintain the original key.
– machineaddict
Sep 27 '13 at 7:04
|
show 6 more comments
PHP 7+
As of PHP 7, this can be done concisely using usort
with an anonymous function that uses the spaceship operator to compare elements.
You can do an ascending sort like this:
usort($inventory, function ($item1, $item2) {
return $item1['price'] <=> $item2['price'];
});
Or a descending sort like this:
usort($inventory, function ($item1, $item2) {
return $item2['price'] <=> $item1['price'];
});
To understand how this works, note that usort
takes a user-provided comparison function that must behave as follows (from the docs):
The comparison function must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second.
And note also that <=>
, the spaceship operator,
returns 0 if both operands are equal, 1 if the left is greater, and -1 if the right is greater
which is exactly what usort
needs. In fact, almost the entire justification given for adding <=>
to the language in https://wiki.php.net/rfc/combined-comparison-operator is that it
makes writing ordering callbacks for use with
usort()
easier
PHP 5.3+
PHP 5.3 introduced anonymous functions, but doesn't yet have the spaceship operator. We can still use usort
to sort our array, but it's a little more verbose and harder to understand:
usort($inventory, function ($item1, $item2) {
if ($item1['price'] == $item2['price']) return 0;
return $item1['price'] < $item2['price'] ? -1 : 1;
});
Note that although it's fairly common for comparators dealing with integer values to just return the difference of the values, like $item2['price'] - $item1['price']
, we can't safely do that in this case. This is because the prices are floating point numbers in the question asker's example, but the comparison function we pass to usort
has to return integers for usort
to work properly:
Returning non-integer values from the comparison function, such as float, will result in an internal cast to integer of the callback's return value. So values such as 0.99 and 0.1 will both be cast to an integer value of 0, which will compare such values as equal.
This is an important trap to bear in mind when using usort
in PHP 5.x! My original version of this answer made this mistake and yet I accrued ten upvotes over thousands of views apparently without anybody noticing the serious bug. The ease with which lackwits like me can screw up comparator functions is precisely the reason that the easier-to-use spaceship operator was added to the language in PHP 7.
6
Sorry, but this approach deletes the string keys from associative arrays. "uasort" function should be used, instead.
– Matteo-SoftNet
Mar 26 '14 at 11:54
7
@DotMat Interesting - I didn't know aboutuasort
. After looking at the docs, though, this answer is still correct in this case. In the OP's example, the array to be sorted has sequential numeric indexes rather than string indexes, sousort
is more appropriate. Usinguasort
on a sequentially-indexed array will result in a sorted array which is not ordered by its numeric indexes, such that the first element seen in aforeach
loop is not$your_array[0]
, which is unlikely to be desirable behaviour.
– Mark Amery
Mar 26 '14 at 12:47
add a comment |
PHP 7+
As of PHP 7, this can be done concisely using usort
with an anonymous function that uses the spaceship operator to compare elements.
You can do an ascending sort like this:
usort($inventory, function ($item1, $item2) {
return $item1['price'] <=> $item2['price'];
});
Or a descending sort like this:
usort($inventory, function ($item1, $item2) {
return $item2['price'] <=> $item1['price'];
});
To understand how this works, note that usort
takes a user-provided comparison function that must behave as follows (from the docs):
The comparison function must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second.
And note also that <=>
, the spaceship operator,
returns 0 if both operands are equal, 1 if the left is greater, and -1 if the right is greater
which is exactly what usort
needs. In fact, almost the entire justification given for adding <=>
to the language in https://wiki.php.net/rfc/combined-comparison-operator is that it
makes writing ordering callbacks for use with
usort()
easier
PHP 5.3+
PHP 5.3 introduced anonymous functions, but doesn't yet have the spaceship operator. We can still use usort
to sort our array, but it's a little more verbose and harder to understand:
usort($inventory, function ($item1, $item2) {
if ($item1['price'] == $item2['price']) return 0;
return $item1['price'] < $item2['price'] ? -1 : 1;
});
Note that although it's fairly common for comparators dealing with integer values to just return the difference of the values, like $item2['price'] - $item1['price']
, we can't safely do that in this case. This is because the prices are floating point numbers in the question asker's example, but the comparison function we pass to usort
has to return integers for usort
to work properly:
Returning non-integer values from the comparison function, such as float, will result in an internal cast to integer of the callback's return value. So values such as 0.99 and 0.1 will both be cast to an integer value of 0, which will compare such values as equal.
This is an important trap to bear in mind when using usort
in PHP 5.x! My original version of this answer made this mistake and yet I accrued ten upvotes over thousands of views apparently without anybody noticing the serious bug. The ease with which lackwits like me can screw up comparator functions is precisely the reason that the easier-to-use spaceship operator was added to the language in PHP 7.
6
Sorry, but this approach deletes the string keys from associative arrays. "uasort" function should be used, instead.
– Matteo-SoftNet
Mar 26 '14 at 11:54
7
@DotMat Interesting - I didn't know aboutuasort
. After looking at the docs, though, this answer is still correct in this case. In the OP's example, the array to be sorted has sequential numeric indexes rather than string indexes, sousort
is more appropriate. Usinguasort
on a sequentially-indexed array will result in a sorted array which is not ordered by its numeric indexes, such that the first element seen in aforeach
loop is not$your_array[0]
, which is unlikely to be desirable behaviour.
– Mark Amery
Mar 26 '14 at 12:47
add a comment |
PHP 7+
As of PHP 7, this can be done concisely using usort
with an anonymous function that uses the spaceship operator to compare elements.
You can do an ascending sort like this:
usort($inventory, function ($item1, $item2) {
return $item1['price'] <=> $item2['price'];
});
Or a descending sort like this:
usort($inventory, function ($item1, $item2) {
return $item2['price'] <=> $item1['price'];
});
To understand how this works, note that usort
takes a user-provided comparison function that must behave as follows (from the docs):
The comparison function must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second.
And note also that <=>
, the spaceship operator,
returns 0 if both operands are equal, 1 if the left is greater, and -1 if the right is greater
which is exactly what usort
needs. In fact, almost the entire justification given for adding <=>
to the language in https://wiki.php.net/rfc/combined-comparison-operator is that it
makes writing ordering callbacks for use with
usort()
easier
PHP 5.3+
PHP 5.3 introduced anonymous functions, but doesn't yet have the spaceship operator. We can still use usort
to sort our array, but it's a little more verbose and harder to understand:
usort($inventory, function ($item1, $item2) {
if ($item1['price'] == $item2['price']) return 0;
return $item1['price'] < $item2['price'] ? -1 : 1;
});
Note that although it's fairly common for comparators dealing with integer values to just return the difference of the values, like $item2['price'] - $item1['price']
, we can't safely do that in this case. This is because the prices are floating point numbers in the question asker's example, but the comparison function we pass to usort
has to return integers for usort
to work properly:
Returning non-integer values from the comparison function, such as float, will result in an internal cast to integer of the callback's return value. So values such as 0.99 and 0.1 will both be cast to an integer value of 0, which will compare such values as equal.
This is an important trap to bear in mind when using usort
in PHP 5.x! My original version of this answer made this mistake and yet I accrued ten upvotes over thousands of views apparently without anybody noticing the serious bug. The ease with which lackwits like me can screw up comparator functions is precisely the reason that the easier-to-use spaceship operator was added to the language in PHP 7.
PHP 7+
As of PHP 7, this can be done concisely using usort
with an anonymous function that uses the spaceship operator to compare elements.
You can do an ascending sort like this:
usort($inventory, function ($item1, $item2) {
return $item1['price'] <=> $item2['price'];
});
Or a descending sort like this:
usort($inventory, function ($item1, $item2) {
return $item2['price'] <=> $item1['price'];
});
To understand how this works, note that usort
takes a user-provided comparison function that must behave as follows (from the docs):
The comparison function must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second.
And note also that <=>
, the spaceship operator,
returns 0 if both operands are equal, 1 if the left is greater, and -1 if the right is greater
which is exactly what usort
needs. In fact, almost the entire justification given for adding <=>
to the language in https://wiki.php.net/rfc/combined-comparison-operator is that it
makes writing ordering callbacks for use with
usort()
easier
PHP 5.3+
PHP 5.3 introduced anonymous functions, but doesn't yet have the spaceship operator. We can still use usort
to sort our array, but it's a little more verbose and harder to understand:
usort($inventory, function ($item1, $item2) {
if ($item1['price'] == $item2['price']) return 0;
return $item1['price'] < $item2['price'] ? -1 : 1;
});
Note that although it's fairly common for comparators dealing with integer values to just return the difference of the values, like $item2['price'] - $item1['price']
, we can't safely do that in this case. This is because the prices are floating point numbers in the question asker's example, but the comparison function we pass to usort
has to return integers for usort
to work properly:
Returning non-integer values from the comparison function, such as float, will result in an internal cast to integer of the callback's return value. So values such as 0.99 and 0.1 will both be cast to an integer value of 0, which will compare such values as equal.
This is an important trap to bear in mind when using usort
in PHP 5.x! My original version of this answer made this mistake and yet I accrued ten upvotes over thousands of views apparently without anybody noticing the serious bug. The ease with which lackwits like me can screw up comparator functions is precisely the reason that the easier-to-use spaceship operator was added to the language in PHP 7.
edited May 23 '17 at 11:47
Community♦
11
11
answered Oct 18 '13 at 16:33


Mark AmeryMark Amery
63.2k31253302
63.2k31253302
6
Sorry, but this approach deletes the string keys from associative arrays. "uasort" function should be used, instead.
– Matteo-SoftNet
Mar 26 '14 at 11:54
7
@DotMat Interesting - I didn't know aboutuasort
. After looking at the docs, though, this answer is still correct in this case. In the OP's example, the array to be sorted has sequential numeric indexes rather than string indexes, sousort
is more appropriate. Usinguasort
on a sequentially-indexed array will result in a sorted array which is not ordered by its numeric indexes, such that the first element seen in aforeach
loop is not$your_array[0]
, which is unlikely to be desirable behaviour.
– Mark Amery
Mar 26 '14 at 12:47
add a comment |
6
Sorry, but this approach deletes the string keys from associative arrays. "uasort" function should be used, instead.
– Matteo-SoftNet
Mar 26 '14 at 11:54
7
@DotMat Interesting - I didn't know aboutuasort
. After looking at the docs, though, this answer is still correct in this case. In the OP's example, the array to be sorted has sequential numeric indexes rather than string indexes, sousort
is more appropriate. Usinguasort
on a sequentially-indexed array will result in a sorted array which is not ordered by its numeric indexes, such that the first element seen in aforeach
loop is not$your_array[0]
, which is unlikely to be desirable behaviour.
– Mark Amery
Mar 26 '14 at 12:47
6
6
Sorry, but this approach deletes the string keys from associative arrays. "uasort" function should be used, instead.
– Matteo-SoftNet
Mar 26 '14 at 11:54
Sorry, but this approach deletes the string keys from associative arrays. "uasort" function should be used, instead.
– Matteo-SoftNet
Mar 26 '14 at 11:54
7
7
@DotMat Interesting - I didn't know about
uasort
. After looking at the docs, though, this answer is still correct in this case. In the OP's example, the array to be sorted has sequential numeric indexes rather than string indexes, so usort
is more appropriate. Using uasort
on a sequentially-indexed array will result in a sorted array which is not ordered by its numeric indexes, such that the first element seen in a foreach
loop is not $your_array[0]
, which is unlikely to be desirable behaviour.– Mark Amery
Mar 26 '14 at 12:47
@DotMat Interesting - I didn't know about
uasort
. After looking at the docs, though, this answer is still correct in this case. In the OP's example, the array to be sorted has sequential numeric indexes rather than string indexes, so usort
is more appropriate. Using uasort
on a sequentially-indexed array will result in a sorted array which is not ordered by its numeric indexes, such that the first element seen in a foreach
loop is not $your_array[0]
, which is unlikely to be desirable behaviour.– Mark Amery
Mar 26 '14 at 12:47
add a comment |
While others have correctly suggested the use of array_multisort()
, for some reason no answer seems to acknowledge the existence of array_column()
, which can greatly simplify the solution. So my suggestion would be:
array_multisort(array_column($inventory, 'price'), SORT_DESC, $inventory);
1
For some reason I was not able to make it work with strings having lower/upper letters. Even using the SORT_FLAG_CASE. The following worked for string comparision for me: array_multisort( array_map(strtolower, array_column($ipr_projects, 'Name')), SORT_ASC, $ipr_projects);
– Pabamato
Apr 19 '18 at 22:36
6
This is the most elegant answer. Should be rated much higher!
– Armin Hierstetter
Aug 1 '18 at 9:44
1
shortest and easiest one, accepted one in my opinion
– StudioX
Dec 15 '18 at 9:38
add a comment |
While others have correctly suggested the use of array_multisort()
, for some reason no answer seems to acknowledge the existence of array_column()
, which can greatly simplify the solution. So my suggestion would be:
array_multisort(array_column($inventory, 'price'), SORT_DESC, $inventory);
1
For some reason I was not able to make it work with strings having lower/upper letters. Even using the SORT_FLAG_CASE. The following worked for string comparision for me: array_multisort( array_map(strtolower, array_column($ipr_projects, 'Name')), SORT_ASC, $ipr_projects);
– Pabamato
Apr 19 '18 at 22:36
6
This is the most elegant answer. Should be rated much higher!
– Armin Hierstetter
Aug 1 '18 at 9:44
1
shortest and easiest one, accepted one in my opinion
– StudioX
Dec 15 '18 at 9:38
add a comment |
While others have correctly suggested the use of array_multisort()
, for some reason no answer seems to acknowledge the existence of array_column()
, which can greatly simplify the solution. So my suggestion would be:
array_multisort(array_column($inventory, 'price'), SORT_DESC, $inventory);
While others have correctly suggested the use of array_multisort()
, for some reason no answer seems to acknowledge the existence of array_column()
, which can greatly simplify the solution. So my suggestion would be:
array_multisort(array_column($inventory, 'price'), SORT_DESC, $inventory);
answered Mar 28 '17 at 21:04
Mariano IglesiasMariano Iglesias
81983
81983
1
For some reason I was not able to make it work with strings having lower/upper letters. Even using the SORT_FLAG_CASE. The following worked for string comparision for me: array_multisort( array_map(strtolower, array_column($ipr_projects, 'Name')), SORT_ASC, $ipr_projects);
– Pabamato
Apr 19 '18 at 22:36
6
This is the most elegant answer. Should be rated much higher!
– Armin Hierstetter
Aug 1 '18 at 9:44
1
shortest and easiest one, accepted one in my opinion
– StudioX
Dec 15 '18 at 9:38
add a comment |
1
For some reason I was not able to make it work with strings having lower/upper letters. Even using the SORT_FLAG_CASE. The following worked for string comparision for me: array_multisort( array_map(strtolower, array_column($ipr_projects, 'Name')), SORT_ASC, $ipr_projects);
– Pabamato
Apr 19 '18 at 22:36
6
This is the most elegant answer. Should be rated much higher!
– Armin Hierstetter
Aug 1 '18 at 9:44
1
shortest and easiest one, accepted one in my opinion
– StudioX
Dec 15 '18 at 9:38
1
1
For some reason I was not able to make it work with strings having lower/upper letters. Even using the SORT_FLAG_CASE. The following worked for string comparision for me: array_multisort( array_map(strtolower, array_column($ipr_projects, 'Name')), SORT_ASC, $ipr_projects);
– Pabamato
Apr 19 '18 at 22:36
For some reason I was not able to make it work with strings having lower/upper letters. Even using the SORT_FLAG_CASE. The following worked for string comparision for me: array_multisort( array_map(strtolower, array_column($ipr_projects, 'Name')), SORT_ASC, $ipr_projects);
– Pabamato
Apr 19 '18 at 22:36
6
6
This is the most elegant answer. Should be rated much higher!
– Armin Hierstetter
Aug 1 '18 at 9:44
This is the most elegant answer. Should be rated much higher!
– Armin Hierstetter
Aug 1 '18 at 9:44
1
1
shortest and easiest one, accepted one in my opinion
– StudioX
Dec 15 '18 at 9:38
shortest and easiest one, accepted one in my opinion
– StudioX
Dec 15 '18 at 9:38
add a comment |
Since your array elements are arrays themselves with string keys, your best bet is to define a custom comparison function. It's pretty quick and easy to do. Try this:
function invenDescSort($item1,$item2)
{
if ($item1['price'] == $item2['price']) return 0;
return ($item1['price'] < $item2['price']) ? 1 : -1;
}
usort($inventory,'invenDescSort');
print_r($inventory);
Produces the following:
Array
(
[0] => Array
(
[type] => pork
[price] => 5.43
)
[1] => Array
(
[type] => fruit
[price] => 3.5
)
[2] => Array
(
[type] => milk
[price] => 2.9
)
)
3
Combining with some of the other comments here (uasort and inline anonymous functions), you get this one-liner:uasort( $inventory, function ($a, $b) { if ( $a==$b ) return 0; else return ($a > $b) ? -1 : 1; });
– Alan Porter
May 1 '14 at 12:44
@AlanPorterusort
seems more appropriate thanuasort
for sorting an array with sequential numeric keys. Ending up with an array where the first element is at index1
and the second element is at index0
is weird behavior and a sure trap for people who aren't familiar with the details of PHP's arrays;usort
gives you the output you'd intuitively expect.
– Mark Amery
May 2 '15 at 23:13
add a comment |
Since your array elements are arrays themselves with string keys, your best bet is to define a custom comparison function. It's pretty quick and easy to do. Try this:
function invenDescSort($item1,$item2)
{
if ($item1['price'] == $item2['price']) return 0;
return ($item1['price'] < $item2['price']) ? 1 : -1;
}
usort($inventory,'invenDescSort');
print_r($inventory);
Produces the following:
Array
(
[0] => Array
(
[type] => pork
[price] => 5.43
)
[1] => Array
(
[type] => fruit
[price] => 3.5
)
[2] => Array
(
[type] => milk
[price] => 2.9
)
)
3
Combining with some of the other comments here (uasort and inline anonymous functions), you get this one-liner:uasort( $inventory, function ($a, $b) { if ( $a==$b ) return 0; else return ($a > $b) ? -1 : 1; });
– Alan Porter
May 1 '14 at 12:44
@AlanPorterusort
seems more appropriate thanuasort
for sorting an array with sequential numeric keys. Ending up with an array where the first element is at index1
and the second element is at index0
is weird behavior and a sure trap for people who aren't familiar with the details of PHP's arrays;usort
gives you the output you'd intuitively expect.
– Mark Amery
May 2 '15 at 23:13
add a comment |
Since your array elements are arrays themselves with string keys, your best bet is to define a custom comparison function. It's pretty quick and easy to do. Try this:
function invenDescSort($item1,$item2)
{
if ($item1['price'] == $item2['price']) return 0;
return ($item1['price'] < $item2['price']) ? 1 : -1;
}
usort($inventory,'invenDescSort');
print_r($inventory);
Produces the following:
Array
(
[0] => Array
(
[type] => pork
[price] => 5.43
)
[1] => Array
(
[type] => fruit
[price] => 3.5
)
[2] => Array
(
[type] => milk
[price] => 2.9
)
)
Since your array elements are arrays themselves with string keys, your best bet is to define a custom comparison function. It's pretty quick and easy to do. Try this:
function invenDescSort($item1,$item2)
{
if ($item1['price'] == $item2['price']) return 0;
return ($item1['price'] < $item2['price']) ? 1 : -1;
}
usort($inventory,'invenDescSort');
print_r($inventory);
Produces the following:
Array
(
[0] => Array
(
[type] => pork
[price] => 5.43
)
[1] => Array
(
[type] => fruit
[price] => 3.5
)
[2] => Array
(
[type] => milk
[price] => 2.9
)
)
answered Oct 20 '09 at 23:04


zombatzombat
76.8k20137157
76.8k20137157
3
Combining with some of the other comments here (uasort and inline anonymous functions), you get this one-liner:uasort( $inventory, function ($a, $b) { if ( $a==$b ) return 0; else return ($a > $b) ? -1 : 1; });
– Alan Porter
May 1 '14 at 12:44
@AlanPorterusort
seems more appropriate thanuasort
for sorting an array with sequential numeric keys. Ending up with an array where the first element is at index1
and the second element is at index0
is weird behavior and a sure trap for people who aren't familiar with the details of PHP's arrays;usort
gives you the output you'd intuitively expect.
– Mark Amery
May 2 '15 at 23:13
add a comment |
3
Combining with some of the other comments here (uasort and inline anonymous functions), you get this one-liner:uasort( $inventory, function ($a, $b) { if ( $a==$b ) return 0; else return ($a > $b) ? -1 : 1; });
– Alan Porter
May 1 '14 at 12:44
@AlanPorterusort
seems more appropriate thanuasort
for sorting an array with sequential numeric keys. Ending up with an array where the first element is at index1
and the second element is at index0
is weird behavior and a sure trap for people who aren't familiar with the details of PHP's arrays;usort
gives you the output you'd intuitively expect.
– Mark Amery
May 2 '15 at 23:13
3
3
Combining with some of the other comments here (uasort and inline anonymous functions), you get this one-liner:
uasort( $inventory, function ($a, $b) { if ( $a==$b ) return 0; else return ($a > $b) ? -1 : 1; });
– Alan Porter
May 1 '14 at 12:44
Combining with some of the other comments here (uasort and inline anonymous functions), you get this one-liner:
uasort( $inventory, function ($a, $b) { if ( $a==$b ) return 0; else return ($a > $b) ? -1 : 1; });
– Alan Porter
May 1 '14 at 12:44
@AlanPorter
usort
seems more appropriate than uasort
for sorting an array with sequential numeric keys. Ending up with an array where the first element is at index 1
and the second element is at index 0
is weird behavior and a sure trap for people who aren't familiar with the details of PHP's arrays; usort
gives you the output you'd intuitively expect.– Mark Amery
May 2 '15 at 23:13
@AlanPorter
usort
seems more appropriate than uasort
for sorting an array with sequential numeric keys. Ending up with an array where the first element is at index 1
and the second element is at index 0
is weird behavior and a sure trap for people who aren't familiar with the details of PHP's arrays; usort
gives you the output you'd intuitively expect.– Mark Amery
May 2 '15 at 23:13
add a comment |
I ended on this:
function sort_array_of_array(&$array, $subfield)
{
$sortarray = array();
foreach ($array as $key => $row)
{
$sortarray[$key] = $row[$subfield];
}
array_multisort($sortarray, SORT_ASC, $array);
}
Just call the function, passing the array and the name of the field of the second level array.
Like:
sort_array_of_array($inventory, 'price');
1
Ha! I just make pretty-much exactly the same thing and was gonna post but saw yours... upvoted.
– Rob Evans
Apr 5 '14 at 21:12
1
Downvoting because this is exactly the same solution that Josh Davis posted years earlier.
– Mark Amery
Oct 22 '15 at 21:44
Disagree... I didn't say it's a different solution, I just said that I ended with this solution and give a full working function.
– Danielzt
Jan 24 '17 at 18:30
1
@MarkAmery I prefer answers contained in functions. It encourages copy pasters to use functions and hopefully write less spaghetti code.
– Goose
Jun 1 '17 at 23:53
add a comment |
I ended on this:
function sort_array_of_array(&$array, $subfield)
{
$sortarray = array();
foreach ($array as $key => $row)
{
$sortarray[$key] = $row[$subfield];
}
array_multisort($sortarray, SORT_ASC, $array);
}
Just call the function, passing the array and the name of the field of the second level array.
Like:
sort_array_of_array($inventory, 'price');
1
Ha! I just make pretty-much exactly the same thing and was gonna post but saw yours... upvoted.
– Rob Evans
Apr 5 '14 at 21:12
1
Downvoting because this is exactly the same solution that Josh Davis posted years earlier.
– Mark Amery
Oct 22 '15 at 21:44
Disagree... I didn't say it's a different solution, I just said that I ended with this solution and give a full working function.
– Danielzt
Jan 24 '17 at 18:30
1
@MarkAmery I prefer answers contained in functions. It encourages copy pasters to use functions and hopefully write less spaghetti code.
– Goose
Jun 1 '17 at 23:53
add a comment |
I ended on this:
function sort_array_of_array(&$array, $subfield)
{
$sortarray = array();
foreach ($array as $key => $row)
{
$sortarray[$key] = $row[$subfield];
}
array_multisort($sortarray, SORT_ASC, $array);
}
Just call the function, passing the array and the name of the field of the second level array.
Like:
sort_array_of_array($inventory, 'price');
I ended on this:
function sort_array_of_array(&$array, $subfield)
{
$sortarray = array();
foreach ($array as $key => $row)
{
$sortarray[$key] = $row[$subfield];
}
array_multisort($sortarray, SORT_ASC, $array);
}
Just call the function, passing the array and the name of the field of the second level array.
Like:
sort_array_of_array($inventory, 'price');
edited Dec 19 '13 at 15:18


zkanoca
5,56053874
5,56053874
answered Nov 23 '12 at 2:52
DanielztDanielzt
36129
36129
1
Ha! I just make pretty-much exactly the same thing and was gonna post but saw yours... upvoted.
– Rob Evans
Apr 5 '14 at 21:12
1
Downvoting because this is exactly the same solution that Josh Davis posted years earlier.
– Mark Amery
Oct 22 '15 at 21:44
Disagree... I didn't say it's a different solution, I just said that I ended with this solution and give a full working function.
– Danielzt
Jan 24 '17 at 18:30
1
@MarkAmery I prefer answers contained in functions. It encourages copy pasters to use functions and hopefully write less spaghetti code.
– Goose
Jun 1 '17 at 23:53
add a comment |
1
Ha! I just make pretty-much exactly the same thing and was gonna post but saw yours... upvoted.
– Rob Evans
Apr 5 '14 at 21:12
1
Downvoting because this is exactly the same solution that Josh Davis posted years earlier.
– Mark Amery
Oct 22 '15 at 21:44
Disagree... I didn't say it's a different solution, I just said that I ended with this solution and give a full working function.
– Danielzt
Jan 24 '17 at 18:30
1
@MarkAmery I prefer answers contained in functions. It encourages copy pasters to use functions and hopefully write less spaghetti code.
– Goose
Jun 1 '17 at 23:53
1
1
Ha! I just make pretty-much exactly the same thing and was gonna post but saw yours... upvoted.
– Rob Evans
Apr 5 '14 at 21:12
Ha! I just make pretty-much exactly the same thing and was gonna post but saw yours... upvoted.
– Rob Evans
Apr 5 '14 at 21:12
1
1
Downvoting because this is exactly the same solution that Josh Davis posted years earlier.
– Mark Amery
Oct 22 '15 at 21:44
Downvoting because this is exactly the same solution that Josh Davis posted years earlier.
– Mark Amery
Oct 22 '15 at 21:44
Disagree... I didn't say it's a different solution, I just said that I ended with this solution and give a full working function.
– Danielzt
Jan 24 '17 at 18:30
Disagree... I didn't say it's a different solution, I just said that I ended with this solution and give a full working function.
– Danielzt
Jan 24 '17 at 18:30
1
1
@MarkAmery I prefer answers contained in functions. It encourages copy pasters to use functions and hopefully write less spaghetti code.
– Goose
Jun 1 '17 at 23:53
@MarkAmery I prefer answers contained in functions. It encourages copy pasters to use functions and hopefully write less spaghetti code.
– Goose
Jun 1 '17 at 23:53
add a comment |
You can use usort
with anonymous function, e.g.
usort($inventory, function ($a, $b) { return strnatcmp($a['price'], $b['price']); });
Versions PHP 5 >= 5.5.0, PHP 7 for those of you like me that really wanted this to work for them..
– Matt P
Feb 21 '18 at 22:43
add a comment |
You can use usort
with anonymous function, e.g.
usort($inventory, function ($a, $b) { return strnatcmp($a['price'], $b['price']); });
Versions PHP 5 >= 5.5.0, PHP 7 for those of you like me that really wanted this to work for them..
– Matt P
Feb 21 '18 at 22:43
add a comment |
You can use usort
with anonymous function, e.g.
usort($inventory, function ($a, $b) { return strnatcmp($a['price'], $b['price']); });
You can use usort
with anonymous function, e.g.
usort($inventory, function ($a, $b) { return strnatcmp($a['price'], $b['price']); });
answered Aug 30 '16 at 16:16
kenorbkenorb
69.2k29407411
69.2k29407411
Versions PHP 5 >= 5.5.0, PHP 7 for those of you like me that really wanted this to work for them..
– Matt P
Feb 21 '18 at 22:43
add a comment |
Versions PHP 5 >= 5.5.0, PHP 7 for those of you like me that really wanted this to work for them..
– Matt P
Feb 21 '18 at 22:43
Versions PHP 5 >= 5.5.0, PHP 7 for those of you like me that really wanted this to work for them..
– Matt P
Feb 21 '18 at 22:43
Versions PHP 5 >= 5.5.0, PHP 7 for those of you like me that really wanted this to work for them..
– Matt P
Feb 21 '18 at 22:43
add a comment |
$inventory =
array(array("type"=>"fruit", "price"=>3.50),
array("type"=>"milk", "price"=>2.90),
array("type"=>"pork", "price"=>5.43),
);
function pricesort($a, $b) {
$a = $a['price'];
$b = $b['price'];
if ($a == $b)
return 0;
return ($a > $b) ? -1 : 1;
}
usort($inventory, "pricesort");
// uksort($inventory, "pricesort");
print("first: ".$inventory[0]['type']."nn");
// for usort(): prints milk (item with lowest price)
// for uksort(): prints fruit (item with key 0 in the original $inventory)
// foreach prints the same for usort and uksort.
foreach($inventory as $i){
print($i['type'].": ".$i['price']."n");
}
outputs:
first: pork
pork: 5.43
fruit: 3.5
milk: 2.9
add a comment |
$inventory =
array(array("type"=>"fruit", "price"=>3.50),
array("type"=>"milk", "price"=>2.90),
array("type"=>"pork", "price"=>5.43),
);
function pricesort($a, $b) {
$a = $a['price'];
$b = $b['price'];
if ($a == $b)
return 0;
return ($a > $b) ? -1 : 1;
}
usort($inventory, "pricesort");
// uksort($inventory, "pricesort");
print("first: ".$inventory[0]['type']."nn");
// for usort(): prints milk (item with lowest price)
// for uksort(): prints fruit (item with key 0 in the original $inventory)
// foreach prints the same for usort and uksort.
foreach($inventory as $i){
print($i['type'].": ".$i['price']."n");
}
outputs:
first: pork
pork: 5.43
fruit: 3.5
milk: 2.9
add a comment |
$inventory =
array(array("type"=>"fruit", "price"=>3.50),
array("type"=>"milk", "price"=>2.90),
array("type"=>"pork", "price"=>5.43),
);
function pricesort($a, $b) {
$a = $a['price'];
$b = $b['price'];
if ($a == $b)
return 0;
return ($a > $b) ? -1 : 1;
}
usort($inventory, "pricesort");
// uksort($inventory, "pricesort");
print("first: ".$inventory[0]['type']."nn");
// for usort(): prints milk (item with lowest price)
// for uksort(): prints fruit (item with key 0 in the original $inventory)
// foreach prints the same for usort and uksort.
foreach($inventory as $i){
print($i['type'].": ".$i['price']."n");
}
outputs:
first: pork
pork: 5.43
fruit: 3.5
milk: 2.9
$inventory =
array(array("type"=>"fruit", "price"=>3.50),
array("type"=>"milk", "price"=>2.90),
array("type"=>"pork", "price"=>5.43),
);
function pricesort($a, $b) {
$a = $a['price'];
$b = $b['price'];
if ($a == $b)
return 0;
return ($a > $b) ? -1 : 1;
}
usort($inventory, "pricesort");
// uksort($inventory, "pricesort");
print("first: ".$inventory[0]['type']."nn");
// for usort(): prints milk (item with lowest price)
// for uksort(): prints fruit (item with key 0 in the original $inventory)
// foreach prints the same for usort and uksort.
foreach($inventory as $i){
print($i['type'].": ".$i['price']."n");
}
outputs:
first: pork
pork: 5.43
fruit: 3.5
milk: 2.9
edited Oct 20 '09 at 23:16
answered Oct 20 '09 at 23:03
danamlunddanamlund
45634
45634
add a comment |
add a comment |
Was tested on 100 000 records:
Time in seconds(calculated by funciton microtime).
Only for unique values on sorting key positions.
Solution of function of @Josh Davis:
Spended time: 1.5768740177155
Mine solution:
Spended time: 0.094044923782349
Solution:
function SortByKeyValue($data, $sortKey, $sort_flags=SORT_ASC)
{
if (empty($data) or empty($sortKey)) return $data;
$ordered = array();
foreach ($data as $key => $value)
$ordered[$value[$sortKey]] = $value;
ksort($ordered, $sort_flags);
return array_values($ordered); *// array_values() added for identical result with multisort*
}
7
The requirement for unique sort keys is sort of a deal breaker, though. If you have unique sort values that can be keys, it begs the question: why not simply construct the array with those keys to begin with? In the OP's scenario, it is difficult to imagine that two items with the same price would be impossible. That in mind, using this solution would cause items from the array to mysteriously and silently disappear from the sorted result set.
– Chris Baker
Dec 4 '13 at 20:41
Thanks. This works for me
– Mahesh
Feb 19 '14 at 10:54
@Chris Baker, you are right. This works only for unique values. But this solution works very fast, so speed was the reason of make and use it. At the moment may be it is not actual, need to test it with PHP 7.1.x.
– Nefelim
Jan 3 '17 at 9:04
add a comment |
Was tested on 100 000 records:
Time in seconds(calculated by funciton microtime).
Only for unique values on sorting key positions.
Solution of function of @Josh Davis:
Spended time: 1.5768740177155
Mine solution:
Spended time: 0.094044923782349
Solution:
function SortByKeyValue($data, $sortKey, $sort_flags=SORT_ASC)
{
if (empty($data) or empty($sortKey)) return $data;
$ordered = array();
foreach ($data as $key => $value)
$ordered[$value[$sortKey]] = $value;
ksort($ordered, $sort_flags);
return array_values($ordered); *// array_values() added for identical result with multisort*
}
7
The requirement for unique sort keys is sort of a deal breaker, though. If you have unique sort values that can be keys, it begs the question: why not simply construct the array with those keys to begin with? In the OP's scenario, it is difficult to imagine that two items with the same price would be impossible. That in mind, using this solution would cause items from the array to mysteriously and silently disappear from the sorted result set.
– Chris Baker
Dec 4 '13 at 20:41
Thanks. This works for me
– Mahesh
Feb 19 '14 at 10:54
@Chris Baker, you are right. This works only for unique values. But this solution works very fast, so speed was the reason of make and use it. At the moment may be it is not actual, need to test it with PHP 7.1.x.
– Nefelim
Jan 3 '17 at 9:04
add a comment |
Was tested on 100 000 records:
Time in seconds(calculated by funciton microtime).
Only for unique values on sorting key positions.
Solution of function of @Josh Davis:
Spended time: 1.5768740177155
Mine solution:
Spended time: 0.094044923782349
Solution:
function SortByKeyValue($data, $sortKey, $sort_flags=SORT_ASC)
{
if (empty($data) or empty($sortKey)) return $data;
$ordered = array();
foreach ($data as $key => $value)
$ordered[$value[$sortKey]] = $value;
ksort($ordered, $sort_flags);
return array_values($ordered); *// array_values() added for identical result with multisort*
}
Was tested on 100 000 records:
Time in seconds(calculated by funciton microtime).
Only for unique values on sorting key positions.
Solution of function of @Josh Davis:
Spended time: 1.5768740177155
Mine solution:
Spended time: 0.094044923782349
Solution:
function SortByKeyValue($data, $sortKey, $sort_flags=SORT_ASC)
{
if (empty($data) or empty($sortKey)) return $data;
$ordered = array();
foreach ($data as $key => $value)
$ordered[$value[$sortKey]] = $value;
ksort($ordered, $sort_flags);
return array_values($ordered); *// array_values() added for identical result with multisort*
}
edited May 15 '13 at 11:39
answered May 15 '13 at 11:24
NefelimNefelim
7016
7016
7
The requirement for unique sort keys is sort of a deal breaker, though. If you have unique sort values that can be keys, it begs the question: why not simply construct the array with those keys to begin with? In the OP's scenario, it is difficult to imagine that two items with the same price would be impossible. That in mind, using this solution would cause items from the array to mysteriously and silently disappear from the sorted result set.
– Chris Baker
Dec 4 '13 at 20:41
Thanks. This works for me
– Mahesh
Feb 19 '14 at 10:54
@Chris Baker, you are right. This works only for unique values. But this solution works very fast, so speed was the reason of make and use it. At the moment may be it is not actual, need to test it with PHP 7.1.x.
– Nefelim
Jan 3 '17 at 9:04
add a comment |
7
The requirement for unique sort keys is sort of a deal breaker, though. If you have unique sort values that can be keys, it begs the question: why not simply construct the array with those keys to begin with? In the OP's scenario, it is difficult to imagine that two items with the same price would be impossible. That in mind, using this solution would cause items from the array to mysteriously and silently disappear from the sorted result set.
– Chris Baker
Dec 4 '13 at 20:41
Thanks. This works for me
– Mahesh
Feb 19 '14 at 10:54
@Chris Baker, you are right. This works only for unique values. But this solution works very fast, so speed was the reason of make and use it. At the moment may be it is not actual, need to test it with PHP 7.1.x.
– Nefelim
Jan 3 '17 at 9:04
7
7
The requirement for unique sort keys is sort of a deal breaker, though. If you have unique sort values that can be keys, it begs the question: why not simply construct the array with those keys to begin with? In the OP's scenario, it is difficult to imagine that two items with the same price would be impossible. That in mind, using this solution would cause items from the array to mysteriously and silently disappear from the sorted result set.
– Chris Baker
Dec 4 '13 at 20:41
The requirement for unique sort keys is sort of a deal breaker, though. If you have unique sort values that can be keys, it begs the question: why not simply construct the array with those keys to begin with? In the OP's scenario, it is difficult to imagine that two items with the same price would be impossible. That in mind, using this solution would cause items from the array to mysteriously and silently disappear from the sorted result set.
– Chris Baker
Dec 4 '13 at 20:41
Thanks. This works for me
– Mahesh
Feb 19 '14 at 10:54
Thanks. This works for me
– Mahesh
Feb 19 '14 at 10:54
@Chris Baker, you are right. This works only for unique values. But this solution works very fast, so speed was the reason of make and use it. At the moment may be it is not actual, need to test it with PHP 7.1.x.
– Nefelim
Jan 3 '17 at 9:04
@Chris Baker, you are right. This works only for unique values. But this solution works very fast, so speed was the reason of make and use it. At the moment may be it is not actual, need to test it with PHP 7.1.x.
– Nefelim
Jan 3 '17 at 9:04
add a comment |
From Sort an array of associative arrays by value of given key in php:
uasort (http://php.net/uasort) allows you to sort an array by your own defined function. In your case, that's simple:
$array = array(
array('price'=>'1000.50','product'=>'test1'),
array('price'=>'8800.50','product'=>'test2'),
array('price'=>'200.0','product'=>'test3')
);
function cmp($a, $b) {
return $a['price'] > $b['price'];
}
uasort($array, "cmp");
1
This answer turned up in the low quality review queue, presumably because you don't provide any explanation of the code. If this code answers the question, consider adding adding some text explaining the code in your answer. This way, you are far more likely to get more upvotes — and help the questioner learn something new.
– lmo
Aug 30 '16 at 23:00
1
hmpf. this is the best answer tho.
– commonpike
Apr 11 '18 at 21:01
add a comment |
From Sort an array of associative arrays by value of given key in php:
uasort (http://php.net/uasort) allows you to sort an array by your own defined function. In your case, that's simple:
$array = array(
array('price'=>'1000.50','product'=>'test1'),
array('price'=>'8800.50','product'=>'test2'),
array('price'=>'200.0','product'=>'test3')
);
function cmp($a, $b) {
return $a['price'] > $b['price'];
}
uasort($array, "cmp");
1
This answer turned up in the low quality review queue, presumably because you don't provide any explanation of the code. If this code answers the question, consider adding adding some text explaining the code in your answer. This way, you are far more likely to get more upvotes — and help the questioner learn something new.
– lmo
Aug 30 '16 at 23:00
1
hmpf. this is the best answer tho.
– commonpike
Apr 11 '18 at 21:01
add a comment |
From Sort an array of associative arrays by value of given key in php:
uasort (http://php.net/uasort) allows you to sort an array by your own defined function. In your case, that's simple:
$array = array(
array('price'=>'1000.50','product'=>'test1'),
array('price'=>'8800.50','product'=>'test2'),
array('price'=>'200.0','product'=>'test3')
);
function cmp($a, $b) {
return $a['price'] > $b['price'];
}
uasort($array, "cmp");
From Sort an array of associative arrays by value of given key in php:
uasort (http://php.net/uasort) allows you to sort an array by your own defined function. In your case, that's simple:
$array = array(
array('price'=>'1000.50','product'=>'test1'),
array('price'=>'8800.50','product'=>'test2'),
array('price'=>'200.0','product'=>'test3')
);
function cmp($a, $b) {
return $a['price'] > $b['price'];
}
uasort($array, "cmp");
edited Apr 11 '18 at 21:04


commonpike
5,34713948
5,34713948
answered May 22 '15 at 6:11
KamalKamal
49056
49056
1
This answer turned up in the low quality review queue, presumably because you don't provide any explanation of the code. If this code answers the question, consider adding adding some text explaining the code in your answer. This way, you are far more likely to get more upvotes — and help the questioner learn something new.
– lmo
Aug 30 '16 at 23:00
1
hmpf. this is the best answer tho.
– commonpike
Apr 11 '18 at 21:01
add a comment |
1
This answer turned up in the low quality review queue, presumably because you don't provide any explanation of the code. If this code answers the question, consider adding adding some text explaining the code in your answer. This way, you are far more likely to get more upvotes — and help the questioner learn something new.
– lmo
Aug 30 '16 at 23:00
1
hmpf. this is the best answer tho.
– commonpike
Apr 11 '18 at 21:01
1
1
This answer turned up in the low quality review queue, presumably because you don't provide any explanation of the code. If this code answers the question, consider adding adding some text explaining the code in your answer. This way, you are far more likely to get more upvotes — and help the questioner learn something new.
– lmo
Aug 30 '16 at 23:00
This answer turned up in the low quality review queue, presumably because you don't provide any explanation of the code. If this code answers the question, consider adding adding some text explaining the code in your answer. This way, you are far more likely to get more upvotes — and help the questioner learn something new.
– lmo
Aug 30 '16 at 23:00
1
1
hmpf. this is the best answer tho.
– commonpike
Apr 11 '18 at 21:01
hmpf. this is the best answer tho.
– commonpike
Apr 11 '18 at 21:01
add a comment |
You might try to define your own comparison function and then use usort.
Yes. I'll do that if I can't find a solution. I'm pretty sure there are some weird parameters you can add to one of the sorts to accomplish this. Thanks for your thoughts though!
– Matt
Oct 20 '09 at 22:58
add a comment |
You might try to define your own comparison function and then use usort.
Yes. I'll do that if I can't find a solution. I'm pretty sure there are some weird parameters you can add to one of the sorts to accomplish this. Thanks for your thoughts though!
– Matt
Oct 20 '09 at 22:58
add a comment |
You might try to define your own comparison function and then use usort.
You might try to define your own comparison function and then use usort.
edited Oct 20 '09 at 23:07
answered Oct 20 '09 at 22:50
Alex SextonAlex Sexton
9,73812339
9,73812339
Yes. I'll do that if I can't find a solution. I'm pretty sure there are some weird parameters you can add to one of the sorts to accomplish this. Thanks for your thoughts though!
– Matt
Oct 20 '09 at 22:58
add a comment |
Yes. I'll do that if I can't find a solution. I'm pretty sure there are some weird parameters you can add to one of the sorts to accomplish this. Thanks for your thoughts though!
– Matt
Oct 20 '09 at 22:58
Yes. I'll do that if I can't find a solution. I'm pretty sure there are some weird parameters you can add to one of the sorts to accomplish this. Thanks for your thoughts though!
– Matt
Oct 20 '09 at 22:58
Yes. I'll do that if I can't find a solution. I'm pretty sure there are some weird parameters you can add to one of the sorts to accomplish this. Thanks for your thoughts though!
– Matt
Oct 20 '09 at 22:58
add a comment |
This function is re-usable:
function usortarr(&$array, $key, $callback = 'strnatcasecmp') {
uasort($array, function($a, $b) use($key, $callback) {
return call_user_func($callback, $a[$key], $b[$key]);
});
}
It works well on string values by default, but you'll have to sub the callback for a number comparison function if all your values are numbers.
add a comment |
This function is re-usable:
function usortarr(&$array, $key, $callback = 'strnatcasecmp') {
uasort($array, function($a, $b) use($key, $callback) {
return call_user_func($callback, $a[$key], $b[$key]);
});
}
It works well on string values by default, but you'll have to sub the callback for a number comparison function if all your values are numbers.
add a comment |
This function is re-usable:
function usortarr(&$array, $key, $callback = 'strnatcasecmp') {
uasort($array, function($a, $b) use($key, $callback) {
return call_user_func($callback, $a[$key], $b[$key]);
});
}
It works well on string values by default, but you'll have to sub the callback for a number comparison function if all your values are numbers.
This function is re-usable:
function usortarr(&$array, $key, $callback = 'strnatcasecmp') {
uasort($array, function($a, $b) use($key, $callback) {
return call_user_func($callback, $a[$key], $b[$key]);
});
}
It works well on string values by default, but you'll have to sub the callback for a number comparison function if all your values are numbers.
edited May 23 '17 at 12:18
Community♦
11
11
answered Apr 11 '16 at 23:19
mpenmpen
125k175654954
125k175654954
add a comment |
add a comment |
//Just in one line custom function
function cmp($a, $b)
{
return (float) $a['price'] < (float)$b['price'];
}
@uasort($inventory, "cmp");
print_r($inventory);
//result
Array
(
[2] => Array
(
[type] => pork
[price] => 5.43
)
[0] => Array
(
[type] => fruit
[price] => 3.5
)
[1] => Array
(
[type] => milk
[price] => 2.9
)
)
add a comment |
//Just in one line custom function
function cmp($a, $b)
{
return (float) $a['price'] < (float)$b['price'];
}
@uasort($inventory, "cmp");
print_r($inventory);
//result
Array
(
[2] => Array
(
[type] => pork
[price] => 5.43
)
[0] => Array
(
[type] => fruit
[price] => 3.5
)
[1] => Array
(
[type] => milk
[price] => 2.9
)
)
add a comment |
//Just in one line custom function
function cmp($a, $b)
{
return (float) $a['price'] < (float)$b['price'];
}
@uasort($inventory, "cmp");
print_r($inventory);
//result
Array
(
[2] => Array
(
[type] => pork
[price] => 5.43
)
[0] => Array
(
[type] => fruit
[price] => 3.5
)
[1] => Array
(
[type] => milk
[price] => 2.9
)
)
//Just in one line custom function
function cmp($a, $b)
{
return (float) $a['price'] < (float)$b['price'];
}
@uasort($inventory, "cmp");
print_r($inventory);
//result
Array
(
[2] => Array
(
[type] => pork
[price] => 5.43
)
[0] => Array
(
[type] => fruit
[price] => 3.5
)
[1] => Array
(
[type] => milk
[price] => 2.9
)
)
edited Sep 20 '14 at 7:15
answered Sep 20 '14 at 7:08
KamalKamal
49056
49056
add a comment |
add a comment |
Here is a method that I found long ago and cleaned up a bit. This works great, and can be quickly changed to accept objects as well.
/**
* A method for sorting arrays by a certain key:value.
* SortByKey is the key you wish to sort by
* Direction can be ASC or DESC.
*
* @param $array
* @param $sortByKey
* @param $sortDirection
* @return array
*/
private function sortArray($array, $sortByKey, $sortDirection) {
$sortArray = array();
$tempArray = array();
foreach ( $array as $key => $value ) {
$tempArray = strtolower( $value[ $sortByKey ] );
}
if($sortDirection=='ASC'){ asort($tempArray ); }
else{ arsort($tempArray ); }
foreach ( $tempArray as $key => $temp ){
$sortArray = $array[ $key ];
}
return $sortArray;
}
to change the method to sort objects simply change the following line:
$tempArray = strtolower( $value[ $sortByKey ] );
to
$tempArray = strtolower( $value->$sortByKey );
To run the method simply do
sortArray($inventory,'price','ASC');
add a comment |
Here is a method that I found long ago and cleaned up a bit. This works great, and can be quickly changed to accept objects as well.
/**
* A method for sorting arrays by a certain key:value.
* SortByKey is the key you wish to sort by
* Direction can be ASC or DESC.
*
* @param $array
* @param $sortByKey
* @param $sortDirection
* @return array
*/
private function sortArray($array, $sortByKey, $sortDirection) {
$sortArray = array();
$tempArray = array();
foreach ( $array as $key => $value ) {
$tempArray = strtolower( $value[ $sortByKey ] );
}
if($sortDirection=='ASC'){ asort($tempArray ); }
else{ arsort($tempArray ); }
foreach ( $tempArray as $key => $temp ){
$sortArray = $array[ $key ];
}
return $sortArray;
}
to change the method to sort objects simply change the following line:
$tempArray = strtolower( $value[ $sortByKey ] );
to
$tempArray = strtolower( $value->$sortByKey );
To run the method simply do
sortArray($inventory,'price','ASC');
add a comment |
Here is a method that I found long ago and cleaned up a bit. This works great, and can be quickly changed to accept objects as well.
/**
* A method for sorting arrays by a certain key:value.
* SortByKey is the key you wish to sort by
* Direction can be ASC or DESC.
*
* @param $array
* @param $sortByKey
* @param $sortDirection
* @return array
*/
private function sortArray($array, $sortByKey, $sortDirection) {
$sortArray = array();
$tempArray = array();
foreach ( $array as $key => $value ) {
$tempArray = strtolower( $value[ $sortByKey ] );
}
if($sortDirection=='ASC'){ asort($tempArray ); }
else{ arsort($tempArray ); }
foreach ( $tempArray as $key => $temp ){
$sortArray = $array[ $key ];
}
return $sortArray;
}
to change the method to sort objects simply change the following line:
$tempArray = strtolower( $value[ $sortByKey ] );
to
$tempArray = strtolower( $value->$sortByKey );
To run the method simply do
sortArray($inventory,'price','ASC');
Here is a method that I found long ago and cleaned up a bit. This works great, and can be quickly changed to accept objects as well.
/**
* A method for sorting arrays by a certain key:value.
* SortByKey is the key you wish to sort by
* Direction can be ASC or DESC.
*
* @param $array
* @param $sortByKey
* @param $sortDirection
* @return array
*/
private function sortArray($array, $sortByKey, $sortDirection) {
$sortArray = array();
$tempArray = array();
foreach ( $array as $key => $value ) {
$tempArray = strtolower( $value[ $sortByKey ] );
}
if($sortDirection=='ASC'){ asort($tempArray ); }
else{ arsort($tempArray ); }
foreach ( $tempArray as $key => $temp ){
$sortArray = $array[ $key ];
}
return $sortArray;
}
to change the method to sort objects simply change the following line:
$tempArray = strtolower( $value[ $sortByKey ] );
to
$tempArray = strtolower( $value->$sortByKey );
To run the method simply do
sortArray($inventory,'price','ASC');
edited Jan 1 at 9:32
answered Jan 1 at 2:41
KrayKray
427720
427720
add a comment |
add a comment |
$arr1 = array(
array('id'=>1,'name'=>'aA','cat'=>'cc'),
array('id'=>2,'name'=>'aa','cat'=>'dd'),
array('id'=>3,'name'=>'bb','cat'=>'cc'),
array('id'=>4,'name'=>'bb','cat'=>'dd')
);
$result1 = array_msort($arr1, array('name'=>SORT_DESC);
$result2 = array_msort($arr1, array('cat'=>SORT_ASC);
$result3 = array_msort($arr1, array('name'=>SORT_DESC, 'cat'=>SORT_ASC));
function array_msort($array, $cols)
{
$colarr = array();
foreach ($cols as $col => $order) {
$colarr[$col] = array();
foreach ($array as $k => $row) { $colarr[$col]['_'.$k] = strtolower($row[$col]); }
}
$eval = 'array_multisort(';
foreach ($cols as $col => $order) {
$eval .= '$colarr[''.$col.''],'.$order.',';
}
$eval = substr($eval,0,-1).');';
eval($eval);
$ret = array();
foreach ($colarr as $col => $arr) {
foreach ($arr as $k => $v) {
$k = substr($k,1);
if (!isset($ret[$k])) $ret[$k] = $array[$k];
$ret[$k][$col] = $array[$k][$col];
}
}
return $ret;
}
While this code snippet may solve the question, including an explanation really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion. Please also try not to crowd your code with explanatory comments, as this reduces the readability of both the code and the explanations!
– FrankerZ
Aug 30 '16 at 20:35
add a comment |
$arr1 = array(
array('id'=>1,'name'=>'aA','cat'=>'cc'),
array('id'=>2,'name'=>'aa','cat'=>'dd'),
array('id'=>3,'name'=>'bb','cat'=>'cc'),
array('id'=>4,'name'=>'bb','cat'=>'dd')
);
$result1 = array_msort($arr1, array('name'=>SORT_DESC);
$result2 = array_msort($arr1, array('cat'=>SORT_ASC);
$result3 = array_msort($arr1, array('name'=>SORT_DESC, 'cat'=>SORT_ASC));
function array_msort($array, $cols)
{
$colarr = array();
foreach ($cols as $col => $order) {
$colarr[$col] = array();
foreach ($array as $k => $row) { $colarr[$col]['_'.$k] = strtolower($row[$col]); }
}
$eval = 'array_multisort(';
foreach ($cols as $col => $order) {
$eval .= '$colarr[''.$col.''],'.$order.',';
}
$eval = substr($eval,0,-1).');';
eval($eval);
$ret = array();
foreach ($colarr as $col => $arr) {
foreach ($arr as $k => $v) {
$k = substr($k,1);
if (!isset($ret[$k])) $ret[$k] = $array[$k];
$ret[$k][$col] = $array[$k][$col];
}
}
return $ret;
}
While this code snippet may solve the question, including an explanation really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion. Please also try not to crowd your code with explanatory comments, as this reduces the readability of both the code and the explanations!
– FrankerZ
Aug 30 '16 at 20:35
add a comment |
$arr1 = array(
array('id'=>1,'name'=>'aA','cat'=>'cc'),
array('id'=>2,'name'=>'aa','cat'=>'dd'),
array('id'=>3,'name'=>'bb','cat'=>'cc'),
array('id'=>4,'name'=>'bb','cat'=>'dd')
);
$result1 = array_msort($arr1, array('name'=>SORT_DESC);
$result2 = array_msort($arr1, array('cat'=>SORT_ASC);
$result3 = array_msort($arr1, array('name'=>SORT_DESC, 'cat'=>SORT_ASC));
function array_msort($array, $cols)
{
$colarr = array();
foreach ($cols as $col => $order) {
$colarr[$col] = array();
foreach ($array as $k => $row) { $colarr[$col]['_'.$k] = strtolower($row[$col]); }
}
$eval = 'array_multisort(';
foreach ($cols as $col => $order) {
$eval .= '$colarr[''.$col.''],'.$order.',';
}
$eval = substr($eval,0,-1).');';
eval($eval);
$ret = array();
foreach ($colarr as $col => $arr) {
foreach ($arr as $k => $v) {
$k = substr($k,1);
if (!isset($ret[$k])) $ret[$k] = $array[$k];
$ret[$k][$col] = $array[$k][$col];
}
}
return $ret;
}
$arr1 = array(
array('id'=>1,'name'=>'aA','cat'=>'cc'),
array('id'=>2,'name'=>'aa','cat'=>'dd'),
array('id'=>3,'name'=>'bb','cat'=>'cc'),
array('id'=>4,'name'=>'bb','cat'=>'dd')
);
$result1 = array_msort($arr1, array('name'=>SORT_DESC);
$result2 = array_msort($arr1, array('cat'=>SORT_ASC);
$result3 = array_msort($arr1, array('name'=>SORT_DESC, 'cat'=>SORT_ASC));
function array_msort($array, $cols)
{
$colarr = array();
foreach ($cols as $col => $order) {
$colarr[$col] = array();
foreach ($array as $k => $row) { $colarr[$col]['_'.$k] = strtolower($row[$col]); }
}
$eval = 'array_multisort(';
foreach ($cols as $col => $order) {
$eval .= '$colarr[''.$col.''],'.$order.',';
}
$eval = substr($eval,0,-1).');';
eval($eval);
$ret = array();
foreach ($colarr as $col => $arr) {
foreach ($arr as $k => $v) {
$k = substr($k,1);
if (!isset($ret[$k])) $ret[$k] = $array[$k];
$ret[$k][$col] = $array[$k][$col];
}
}
return $ret;
}
edited Dec 19 '13 at 15:19


zkanoca
5,56053874
5,56053874
answered Dec 12 '13 at 12:22
Chirag PipariyaChirag Pipariya
309312
309312
While this code snippet may solve the question, including an explanation really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion. Please also try not to crowd your code with explanatory comments, as this reduces the readability of both the code and the explanations!
– FrankerZ
Aug 30 '16 at 20:35
add a comment |
While this code snippet may solve the question, including an explanation really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion. Please also try not to crowd your code with explanatory comments, as this reduces the readability of both the code and the explanations!
– FrankerZ
Aug 30 '16 at 20:35
While this code snippet may solve the question, including an explanation really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion. Please also try not to crowd your code with explanatory comments, as this reduces the readability of both the code and the explanations!
– FrankerZ
Aug 30 '16 at 20:35
While this code snippet may solve the question, including an explanation really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion. Please also try not to crowd your code with explanatory comments, as this reduces the readability of both the code and the explanations!
– FrankerZ
Aug 30 '16 at 20:35
add a comment |
Complete Dynamic Function
I jumped here for associative array sorting and found this amazing function on http://php.net/manual/en/function.sort.php. This function is very dynamic that sort in ascending and descending order with specified key.
Simple function to sort an array by a specific key. Maintains index association
<?php
function array_sort($array, $on, $order=SORT_ASC)
{
$new_array = array();
$sortable_array = array();
if (count($array) > 0) {
foreach ($array as $k => $v) {
if (is_array($v)) {
foreach ($v as $k2 => $v2) {
if ($k2 == $on) {
$sortable_array[$k] = $v2;
}
}
} else {
$sortable_array[$k] = $v;
}
}
switch ($order) {
case SORT_ASC:
asort($sortable_array);
break;
case SORT_DESC:
arsort($sortable_array);
break;
}
foreach ($sortable_array as $k => $v) {
$new_array[$k] = $array[$k];
}
}
return $new_array;
}
$people = array(
12345 => array(
'id' => 12345,
'first_name' => 'Joe',
'surname' => 'Bloggs',
'age' => 23,
'sex' => 'm'
),
12346 => array(
'id' => 12346,
'first_name' => 'Adam',
'surname' => 'Smith',
'age' => 18,
'sex' => 'm'
),
12347 => array(
'id' => 12347,
'first_name' => 'Amy',
'surname' => 'Jones',
'age' => 21,
'sex' => 'f'
)
);
print_r(array_sort($people, 'age', SORT_DESC)); // Sort by oldest first
print_r(array_sort($people, 'surname', SORT_ASC)); // Sort by surname
add a comment |
Complete Dynamic Function
I jumped here for associative array sorting and found this amazing function on http://php.net/manual/en/function.sort.php. This function is very dynamic that sort in ascending and descending order with specified key.
Simple function to sort an array by a specific key. Maintains index association
<?php
function array_sort($array, $on, $order=SORT_ASC)
{
$new_array = array();
$sortable_array = array();
if (count($array) > 0) {
foreach ($array as $k => $v) {
if (is_array($v)) {
foreach ($v as $k2 => $v2) {
if ($k2 == $on) {
$sortable_array[$k] = $v2;
}
}
} else {
$sortable_array[$k] = $v;
}
}
switch ($order) {
case SORT_ASC:
asort($sortable_array);
break;
case SORT_DESC:
arsort($sortable_array);
break;
}
foreach ($sortable_array as $k => $v) {
$new_array[$k] = $array[$k];
}
}
return $new_array;
}
$people = array(
12345 => array(
'id' => 12345,
'first_name' => 'Joe',
'surname' => 'Bloggs',
'age' => 23,
'sex' => 'm'
),
12346 => array(
'id' => 12346,
'first_name' => 'Adam',
'surname' => 'Smith',
'age' => 18,
'sex' => 'm'
),
12347 => array(
'id' => 12347,
'first_name' => 'Amy',
'surname' => 'Jones',
'age' => 21,
'sex' => 'f'
)
);
print_r(array_sort($people, 'age', SORT_DESC)); // Sort by oldest first
print_r(array_sort($people, 'surname', SORT_ASC)); // Sort by surname
add a comment |
Complete Dynamic Function
I jumped here for associative array sorting and found this amazing function on http://php.net/manual/en/function.sort.php. This function is very dynamic that sort in ascending and descending order with specified key.
Simple function to sort an array by a specific key. Maintains index association
<?php
function array_sort($array, $on, $order=SORT_ASC)
{
$new_array = array();
$sortable_array = array();
if (count($array) > 0) {
foreach ($array as $k => $v) {
if (is_array($v)) {
foreach ($v as $k2 => $v2) {
if ($k2 == $on) {
$sortable_array[$k] = $v2;
}
}
} else {
$sortable_array[$k] = $v;
}
}
switch ($order) {
case SORT_ASC:
asort($sortable_array);
break;
case SORT_DESC:
arsort($sortable_array);
break;
}
foreach ($sortable_array as $k => $v) {
$new_array[$k] = $array[$k];
}
}
return $new_array;
}
$people = array(
12345 => array(
'id' => 12345,
'first_name' => 'Joe',
'surname' => 'Bloggs',
'age' => 23,
'sex' => 'm'
),
12346 => array(
'id' => 12346,
'first_name' => 'Adam',
'surname' => 'Smith',
'age' => 18,
'sex' => 'm'
),
12347 => array(
'id' => 12347,
'first_name' => 'Amy',
'surname' => 'Jones',
'age' => 21,
'sex' => 'f'
)
);
print_r(array_sort($people, 'age', SORT_DESC)); // Sort by oldest first
print_r(array_sort($people, 'surname', SORT_ASC)); // Sort by surname
Complete Dynamic Function
I jumped here for associative array sorting and found this amazing function on http://php.net/manual/en/function.sort.php. This function is very dynamic that sort in ascending and descending order with specified key.
Simple function to sort an array by a specific key. Maintains index association
<?php
function array_sort($array, $on, $order=SORT_ASC)
{
$new_array = array();
$sortable_array = array();
if (count($array) > 0) {
foreach ($array as $k => $v) {
if (is_array($v)) {
foreach ($v as $k2 => $v2) {
if ($k2 == $on) {
$sortable_array[$k] = $v2;
}
}
} else {
$sortable_array[$k] = $v;
}
}
switch ($order) {
case SORT_ASC:
asort($sortable_array);
break;
case SORT_DESC:
arsort($sortable_array);
break;
}
foreach ($sortable_array as $k => $v) {
$new_array[$k] = $array[$k];
}
}
return $new_array;
}
$people = array(
12345 => array(
'id' => 12345,
'first_name' => 'Joe',
'surname' => 'Bloggs',
'age' => 23,
'sex' => 'm'
),
12346 => array(
'id' => 12346,
'first_name' => 'Adam',
'surname' => 'Smith',
'age' => 18,
'sex' => 'm'
),
12347 => array(
'id' => 12347,
'first_name' => 'Amy',
'surname' => 'Jones',
'age' => 21,
'sex' => 'f'
)
);
print_r(array_sort($people, 'age', SORT_DESC)); // Sort by oldest first
print_r(array_sort($people, 'surname', SORT_ASC)); // Sort by surname
answered Sep 29 '17 at 14:27


Ahmad SayeedAhmad Sayeed
11418
11418
add a comment |
add a comment |
<?php
$inventory = array(
array("type"=>"fruit", "price"=>3.50),
array("type"=>"milk", "price"=>2.90),
array("type"=>"pork", "price"=>5.43),
);
function myfunc($a,$b){
return strnatcmp($a['price'],$b['price']);
}
$result=usort ($inventory,"myfunc");?>
<pre><?php print_r(array_reverse($inventory)); ?></pre>
the simple solution :)
the output is,
Array
(
[0] => Array
(
[type] => pork
[price] => 5.43
)
[1] => Array
(
[type] => fruit
[price] => 3.5
)
[2] => Array
(
[type] => milk
[price] => 2.9
)
)
This answer turned up in the low quality review queue, presumably because you don't provide any explanation of the code. If this code answers the question, consider adding adding some text explaining the code in your answer. This way, you are far more likely to get more upvotes — and help the questioner learn something new.
– lmo
Aug 30 '16 at 23:02
add a comment |
<?php
$inventory = array(
array("type"=>"fruit", "price"=>3.50),
array("type"=>"milk", "price"=>2.90),
array("type"=>"pork", "price"=>5.43),
);
function myfunc($a,$b){
return strnatcmp($a['price'],$b['price']);
}
$result=usort ($inventory,"myfunc");?>
<pre><?php print_r(array_reverse($inventory)); ?></pre>
the simple solution :)
the output is,
Array
(
[0] => Array
(
[type] => pork
[price] => 5.43
)
[1] => Array
(
[type] => fruit
[price] => 3.5
)
[2] => Array
(
[type] => milk
[price] => 2.9
)
)
This answer turned up in the low quality review queue, presumably because you don't provide any explanation of the code. If this code answers the question, consider adding adding some text explaining the code in your answer. This way, you are far more likely to get more upvotes — and help the questioner learn something new.
– lmo
Aug 30 '16 at 23:02
add a comment |
<?php
$inventory = array(
array("type"=>"fruit", "price"=>3.50),
array("type"=>"milk", "price"=>2.90),
array("type"=>"pork", "price"=>5.43),
);
function myfunc($a,$b){
return strnatcmp($a['price'],$b['price']);
}
$result=usort ($inventory,"myfunc");?>
<pre><?php print_r(array_reverse($inventory)); ?></pre>
the simple solution :)
the output is,
Array
(
[0] => Array
(
[type] => pork
[price] => 5.43
)
[1] => Array
(
[type] => fruit
[price] => 3.5
)
[2] => Array
(
[type] => milk
[price] => 2.9
)
)
<?php
$inventory = array(
array("type"=>"fruit", "price"=>3.50),
array("type"=>"milk", "price"=>2.90),
array("type"=>"pork", "price"=>5.43),
);
function myfunc($a,$b){
return strnatcmp($a['price'],$b['price']);
}
$result=usort ($inventory,"myfunc");?>
<pre><?php print_r(array_reverse($inventory)); ?></pre>
the simple solution :)
the output is,
Array
(
[0] => Array
(
[type] => pork
[price] => 5.43
)
[1] => Array
(
[type] => fruit
[price] => 3.5
)
[2] => Array
(
[type] => milk
[price] => 2.9
)
)
answered Aug 4 '14 at 5:22


AkhilhhAkhilhh
471410
471410
This answer turned up in the low quality review queue, presumably because you don't provide any explanation of the code. If this code answers the question, consider adding adding some text explaining the code in your answer. This way, you are far more likely to get more upvotes — and help the questioner learn something new.
– lmo
Aug 30 '16 at 23:02
add a comment |
This answer turned up in the low quality review queue, presumably because you don't provide any explanation of the code. If this code answers the question, consider adding adding some text explaining the code in your answer. This way, you are far more likely to get more upvotes — and help the questioner learn something new.
– lmo
Aug 30 '16 at 23:02
This answer turned up in the low quality review queue, presumably because you don't provide any explanation of the code. If this code answers the question, consider adding adding some text explaining the code in your answer. This way, you are far more likely to get more upvotes — and help the questioner learn something new.
– lmo
Aug 30 '16 at 23:02
This answer turned up in the low quality review queue, presumably because you don't provide any explanation of the code. If this code answers the question, consider adding adding some text explaining the code in your answer. This way, you are far more likely to get more upvotes — and help the questioner learn something new.
– lmo
Aug 30 '16 at 23:02
add a comment |
try this:
asort($array_to_sort, SORT_NUMERIC);
for reference see this:
http://php.net/manual/en/function.asort.php
see various sort flags here:
http://www.php.net/manual/en/function.sort.php
this won't work for multidimensional arrays, but just helped me out for another problem, thanks :)
– schellmax
Feb 3 '12 at 12:13
4
This can't be used to sort a list of dictionaries by a particular dictionary key, and hence doesn't answer the question posed.
– Mark Amery
Oct 18 '13 at 16:19
add a comment |
try this:
asort($array_to_sort, SORT_NUMERIC);
for reference see this:
http://php.net/manual/en/function.asort.php
see various sort flags here:
http://www.php.net/manual/en/function.sort.php
this won't work for multidimensional arrays, but just helped me out for another problem, thanks :)
– schellmax
Feb 3 '12 at 12:13
4
This can't be used to sort a list of dictionaries by a particular dictionary key, and hence doesn't answer the question posed.
– Mark Amery
Oct 18 '13 at 16:19
add a comment |
try this:
asort($array_to_sort, SORT_NUMERIC);
for reference see this:
http://php.net/manual/en/function.asort.php
see various sort flags here:
http://www.php.net/manual/en/function.sort.php
try this:
asort($array_to_sort, SORT_NUMERIC);
for reference see this:
http://php.net/manual/en/function.asort.php
see various sort flags here:
http://www.php.net/manual/en/function.sort.php
edited Dec 19 '13 at 15:17


zkanoca
5,56053874
5,56053874
answered Oct 20 '09 at 23:02
sarsnakesarsnake
10.1k54153271
10.1k54153271
this won't work for multidimensional arrays, but just helped me out for another problem, thanks :)
– schellmax
Feb 3 '12 at 12:13
4
This can't be used to sort a list of dictionaries by a particular dictionary key, and hence doesn't answer the question posed.
– Mark Amery
Oct 18 '13 at 16:19
add a comment |
this won't work for multidimensional arrays, but just helped me out for another problem, thanks :)
– schellmax
Feb 3 '12 at 12:13
4
This can't be used to sort a list of dictionaries by a particular dictionary key, and hence doesn't answer the question posed.
– Mark Amery
Oct 18 '13 at 16:19
this won't work for multidimensional arrays, but just helped me out for another problem, thanks :)
– schellmax
Feb 3 '12 at 12:13
this won't work for multidimensional arrays, but just helped me out for another problem, thanks :)
– schellmax
Feb 3 '12 at 12:13
4
4
This can't be used to sort a list of dictionaries by a particular dictionary key, and hence doesn't answer the question posed.
– Mark Amery
Oct 18 '13 at 16:19
This can't be used to sort a list of dictionaries by a particular dictionary key, and hence doesn't answer the question posed.
– Mark Amery
Oct 18 '13 at 16:19
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f1597736%2fhow-to-sort-an-array-of-associative-arrays-by-value-of-a-given-key-in-php%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
3
possible duplicate of How do I sort a multidimensional array in php
– Jon
Jul 26 '13 at 9:33
If you are using Eloquent ORM, here's a nice answer.
– Pathros
Jan 20 '16 at 20:02