How do I sort a multidimensional array by one of the fields of the inner array in PHP?
You need to use usort, a function that sorts arrays via a user defined function. Something like:
function cmp($a, $b)
{
if ($a["price"] == $b["price"]) {
return 0;
}
return ($a["price"] < $b["price"]) ? -1 : 1;
}
usort($yourArray,"cmp")
Sort PHP multi-dimensional array based on value in inner array?
Thinking,more useful and practical
http://php.net/manual/en/function.sort.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;
}
How to use
$list = array(
array( 'type' => 'suite', 'name'=>'A-Name'),
array( 'type' => 'suite', 'name'=>'C-Name'),
array( 'type' => 'suite', 'name'=>'B-Name')
);
$list = array_sort($list, 'name', SORT_ASC);
array(3) { [0]=> array(2) { ["type"]=> string(5) "suite" ["name"]=> string(6) "A-Name" } [2]=> array(2) { ["type"]=> string(5) "suite" ["name"]=> string(6) "B-Name" } [1]=> array(2) { ["type"]=> string(5) "suite" ["name"]=> string(6) "C-Name" } }
How to Sort a Multi-dimensional Array by Value
Try a usort. If you are still on PHP 5.2 or earlier, you'll have to define a sorting function first:
function sortByOrder($a, $b) {
return $a['order'] - $b['order'];
}
usort($myArray, 'sortByOrder');
Starting in PHP 5.3, you can use an anonymous function:
usort($myArray, function($a, $b) {
return $a['order'] - $b['order'];
});
With PHP 7 you can use the spaceship operator:
usort($myArray, function($a, $b) {
return $a['order'] <=> $b['order'];
});
Finally, in PHP 7.4 you can clean up a bit with an arrow function:
usort($myArray, fn($a, $b) => $a['order'] <=> $b['order']);
To extend this to multi-dimensional sorting, reference the second/third sorting elements if the first is zero - best explained below. You can also use this for sorting on sub-elements.
usort($myArray, function($a, $b) {
$retval = $a['order'] <=> $b['order'];
if ($retval == 0) {
$retval = $a['suborder'] <=> $b['suborder'];
if ($retval == 0) {
$retval = $a['details']['subsuborder'] <=> $b['details']['subsuborder'];
}
}
return $retval;
});
If you need to retain key associations, use uasort()
- see comparison of array sorting functions in the manual.
Sort multidimensional array based on 2nd element of the subarray
list.sort
, sorted
accept optional key
parameter. key
function is used to generate comparison key.
>>> sorted(lst, key=lambda x: x[1], reverse=True)
[['I', 219], ['A', 22], ['P', 14], ['V', 13], ['G', 10], ...]
>>> sorted(lst, key=lambda x: -x[1])
[['I', 219], ['A', 22], ['P', 14], ['V', 13], ['G', 10], ...]
>>> import operator
>>> sorted(lst, key=operator.itemgetter(1), reverse=True)
[['I', 219], ['A', 22], ['P', 14], ['V', 13], ['G', 10], ...]
Sort php multidimensional array by key value
try below solution:
<?php
$array = Array
(
'2' => Array
(
'66' => Array
(
'id' => 66 ,
'count' => 9
),
'255' => Array
(
'id' => 255,
'count' => 20
)
),
'1' => Array
(
'59' => Array
(
'id' => 59,
'count' => 14
),
'255' => Array
(
'id' => 255,
'count' => 73
)
)
);
echo '<pre>';
foreach($array as &$ar){
usort($ar, function($a, $b) {
return $b['count'] - $a['count'];
});
}
print_r($array);
Output:
Array
(
[2] => Array
(
[0] => Array
(
[id] => 255
[count] => 20
)
[1] => Array
(
[id] => 66
[count] => 9
)
)
[1] => Array
(
[0] => Array
(
[id] => 255
[count] => 73
)
[1] => Array
(
[id] => 59
[count] => 14
)
)
)
PHP sort 2d array alphabetically by nested value
You should use usort() (i'm assuming PHP 5.3+ here):
usort($your_array, function ($elem1, $elem2) {
return strcmp($elem1['title'], $elem2['title']);
});
Edit:
I hadn't noticed you wanted to preserve index association, so you actually need to use uasort()
instead, with the same parameters.
Edit2:
Here is the pre-PHP 5.3 version:
function compareElems($elem1, $elem2) {
return strcmp($elem1['title'], $elem2['title']);
}
uasort($your_array, "compareElems");
Related Topics
How to Keep Whitespace Formatting Using PHP/Html
Pdo Were Rows Affected During Execute Statement
How to Create Clean Url Using .Htaccess
Simplexml Get Element Content Based on Attribute Value
Storing Time Information: Timezone Required
How to Add Two Strings Together
Fatal Error: Call to a Member Function Bindparam()
How to Get the File Path in HTML <Input Type="File"> in PHP
Fatal Error: Call to a Member Function Prepare() on a Non-Object In
How to Deploy Correctly When Using Composer's Develop/Production Switch
Calling a Function Within a Class Method
Linux - PHP 7.0 and Mssql (Microsoft SQL)
Browscap Ini Directive Not Set
How to Ipc Between PHP Clients and a C Daemon Server