Forum Moderators: coopster
Array
(
[Product] => Widgets
[Colour] => Green
[Material] => Rubber
)
Array
(
[0] => Colour
[1] => Material
[2] => Product
)
$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);
Array
(
[Colour] => Green
[Material] => Rubber
[Product] => Widgets
)
to output Green, rubber, widgets.
foreach ($sortOrder as $element) {
echo $arrayToSort[$element].PHP_EOL;
}
Green
Rubber
Widgets
<?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"
}