I have two multi-dimensional arrays and need to sort the first array in the same order as the second array based on different keys (but their values are the same). In the below example I need $allOptions
to be sorted into the same order as $regOptions
but based on the values of clID == optID
.
However, not all $allOptions
sub-arrays (clID) are present in $regOptions
sub-arrays (optID)….so any non-matched elements in $allOptions
would be thrown to the bottom/end of the array.
How can I do this?
$allOptions = array(
array("clID"=> 171, ...other values),
array("clID"=> 191, ...other values),
array("clID"=> 131, ...other values),
array("clID"=> 101, ...other values),
array("clID"=> 201, ...other values),
array("clID"=> 181, ...other values),
...
array("clID"=> 99, ...other values), // not in regOptions
array("clID"=> 129, ...other values) // not in regOptions
array("clID"=> 139, ...other values)
) ;
$regOptions = array(
array("order"=>1,"optID"=> 131, ...other values),
array("order"=>2,"optID"=> 191, ...other values),
array("order"=>3,"optID"=> 181, ...other values),
array("order"=>4,"optID"=> 139, ...other values),
array("order"=>5,"optID"=> 101, ...other values),
array("order"=>6,"optID"=> 201, ...other values),
array("order"=>7,"optID"=> 171, ...other values)
...
) ;
So the output would be:
$allOptions = array(
array("clID"=> 131, ...other values),
array("clID"=> 191, ...other values),
array("clID"=> 181, ...other values),
array("clID"=> 139, ...other values)
array("clID"=> 101, ...other values),
array("clID"=> 201, ...other values),
array("clID"=> 171, ...other values),
...
array("clID"=> 99, ...other values), // not in regOptions
array("clID"=> 129, ...other values) // not in regOptions
) ;
3
Answers
Use php usort()
Example
Here is a solution not based on
array_search()
:Result:
Another option to sorting would be iterating over
$regOptions
and building a new array from$allOptions
, and then appending any items not found to the end.Output: