I have a multi-dimensional array in PHP that looks similar to:
$my_array_to_sort = [ "data" => [ [ "name" => "orange", "id" => 23423, ], [ "name" => "green", "id" => 34343, ], [ "name" => "red", "id" => 65566, ], ], ];
I would like to re-sort this array based on name while keeping its structure and data using a sorting array that looks like this:
$priority = [ "red" => 1, "orange" => 2, "green" => 3, ];
so that the final sort would result in
Array ( [data] => Array ( [0] => Array ( [name] => red [id] => 65566 ) [1] => Array ( [name] => orange [id] => 23423 ) [2] => Array ( [name] => green [id] => 34343 ) ) )
Is uasort() the way to go here? Any code references would be much appreciated.
Advertisement
Answer
You don’t need uasort
as you are not trying to preserve keys in the array you are sorting. usort
will suffice, passing the $priority
array to the callback and sorting based on the priority of each entries name:
usort($my_array_to_sort['data'], function ($a, $b) use ($priority) { return $priority[$a['name']] - $priority[$b['name']]; }); print_r($my_array_to_sort);
Output:
Array ( [data] => Array ( [0] => Array ( [name] => red [id] => 65566 ) [1] => Array ( [name] => orange [id] => 23423 ) [2] => Array ( [name] => green [id] => 34343 ) ) )
To sort in reverse order, simply change the order of variables in the return
expression:
usort($my_array_to_sort['data'], function ($a, $b) use ($priority) { return $priority[$b['name']] - $priority[$a['name']]; });