How to Sort a Multidimensional Array by One of the Fields of the Inner Array in PHP

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")

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 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" } }

Sort multidimensional array by multiple columns

You need array_multisort

$mylist = array(
array('ID' => 1, 'title' => 'Boring Meeting', 'event_type' => 'meeting'),
array('ID' => 2, 'title' => 'Find My Stapler', 'event_type' => 'meeting'),
array('ID' => 3, 'title' => 'Mario Party', 'event_type' => 'party'),
array('ID' => 4, 'title' => 'Duct Tape Party', 'event_type' => 'party')
);

# get a list of sort columns and their data to pass to array_multisort
$sort = array();
foreach($mylist as $k=>$v) {
$sort['title'][$k] = $v['title'];
$sort['event_type'][$k] = $v['event_type'];
}
# sort by event_type desc and then title asc
array_multisort($sort['event_type'], SORT_DESC, $sort['title'], SORT_ASC,$mylist);

As of PHP 5.5.0:

array_multisort(array_column($mylist, 'event_type'), SORT_DESC,
array_column($mylist, 'title'), SORT_ASC,
$mylist);

$mylist is now:

array (
0 =>
array (
'ID' => 4,
'title' => 'Duct Tape Party',
'event_type' => 'party',
),
1 =>
array (
'ID' => 3,
'title' => 'Mario Party',
'event_type' => 'party',
),
2 =>
array (
'ID' => 1,
'title' => 'Boring Meeting',
'event_type' => 'meeting',
),
3 =>
array (
'ID' => 2,
'title' => 'Find My Stapler',
'event_type' => 'meeting',
),
)

How to sort a multidimensional array by multiple columns?

Fundamentally we're going to use the same approach as explained here, we're just going to do it with a variable number of keys:

/**
* Returns a comparison function to sort by $cmp
* over multiple keys. First argument is the comparison
* function, all following arguments are the keys to
* sort by.
*/
function createMultiKeyCmpFunc($cmp, $key /* , keys... */) {
$keys = func_get_args();
array_shift($keys);

return function (array $a, array $b) use ($cmp, $keys) {
return array_reduce($keys, function ($result, $key) use ($cmp, $a, $b) {
return $result ?: call_user_func($cmp, $a[$key], $b[$key]);
});
};
}

usort($array, createMultiKeyCmpFunc('strcmp', 'foo', 'bar', 'baz'));
// or
usort($array, createMultiKeyCmpFunc(function ($a, $b) { return $a - $b; }, 'foo', 'bar', 'baz'));

That's about equivalent to an SQL ORDER BY foo, bar, baz.

If of course each key requires a different kind of comparison logic and you cannot use a general strcmp or - for all keys, you're back to the same code as explained here.

How do I sort a PHP array by an element nested inside?

You can use usort as:

function cmp($a, $b) {
return $a['weight'] - $b['weight'];
}

usort($arr,"cmp");

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");

How do I sort a multidimensional array with stdClass Objects by values of a key?

You're almost right, but $row[$col] tries to access the objects like an array. You want something like $row->{$col} instead. Here's a simpler, working example:

$db = array(
0 => (object) array('name' => 'Business3'),
1 => (object) array('name' => 'Business2'),
2 => (object) array('name' => 'Business1')
);

$col = 'name';
$sort = array();
foreach ($db as $i => $obj) {
$sort[$i] = $obj->{$col};
}

$sorted_db = array_multisort($sort, SORT_ASC, $db);

print_r($db);

Outputs:

Array
(
[0] => stdClass Object
(
[name] => Business1
)

[1] => stdClass Object
(
[name] => Business2
)

[2] => stdClass Object
(
[name] => Business3
)

)


Related Topics



Leave a reply



Submit