Forum Moderators: coopster

Message Too Old, No Replies

Sorting a PHP array by a "priority" array

         

Andy Langton

8:44 pm on Jun 30, 2020 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



I have an array in this format:


Array
(
[Product] => Widgets
[Colour] => Green
[Material] => Rubber
)


And a second array in this format:


Array
(
[0] => Colour
[1] => Material
[2] => Product
)


I want to sort the first array by the "priority" of the index of the second array, e.g. to output Green, rubber, widgets.

I believe usort is the function I need, but I'm struggling to find the right function for the sorting aspect. Any help appreciated!

w3dk

10:30 pm on Jun 30, 2020 (gmt 0)

10+ Year Member Top Contributors Of The Month



It would be easier if the array to sort by had the keys/values the other way round. ie. [Colour] => 0, etc. Then we could do a simple array lookup to get the relative ordering. As it is, we need to perform two searches on the sort-order array with every search operation (in order to retrieve the keys that determine the search order) - this isn't going to be too efficient.

usort() orders an array by values and issues new keys. However, the sort order is determined by keys, not values. usort() also overwrites the keys, which may not be desirable.

You could do the following using uksort() (sorts by keys and preserves assoc keys).


$arrayToSort = Array (
'Product' => 'Widgets',
'Colour' => 'Green',
'Material' => 'Rubber',
);
$sortOrder = Array (
0 => 'Colour',
1 => 'Material',
2 => 'Product',
);

uksort($arrayToSort, function($a,$b) use ($sortOrder) {
return (array_search($a,$sortOrder) > array_search($b,$sortOrder)) ? 1 : -1;
});
print_r($arrayToSort);


Which outputs:


Array
(
[Colour] => Green
[Material] => Rubber
[Product] => Widgets
)


to output Green, rubber, widgets.


HOWEVER, do you need to actually sort the array, or do you just want to output the data in the correct order? If the later then you may not need to sort anything... just traverse the $sortOrder array (which is presumably already in the correct order? If not then sort this array instead) and get the values from $arrayToSort.

For example:


foreach ($sortOrder as $element) {
echo $arrayToSort[$element].PHP_EOL;
}


Output:


Green
Rubber
Widgets

nordberg25

10:05 am on Aug 9, 2020 (gmt 0)

5+ Year Member



<?php
$arr1 = array(Product => Widgets, Colour => Green, Material => Rubber);

$arr2 = array(0 => Colour, 1 => Material, 2 => Product);
/*Switch the value and key of 2nd array with array_flip, since keys match now use array_merge to replace array 2's values with array 1's values*/
$arraymerged = array_merge(array_flip($arr2), $arr1);

var_dump($arraymerged);

?>


Output of var_dump
array(3) {
["Colour"]=>
string(5) "Green"
["Material"]=>
string(6) "Rubber"
["Product"]=>
string(7) "Widgets"
}