Reputation: 12039
I have two arrays, one is linear array indicates sorted list that will be followed to sort and another is associative array that will be sorted.
Here, $recommended_props
is sorted list and $prop_array
is the associative that I want to sort depending on sorted list. Sorted list indicate the property code and I want to sort my array based on this code index.
My arrays are
//Sorted list of property codes
$recommended_props = [29822, 24785, 45875, 45872];
//Property details and this array will be sorted
$prop_array = [
[
'code' => 24785,
'price' => 120,
'currency' => 'USD',
],
[
'code' => 29822,
'price' => 150,
'currency' => 'USD',
],
[
'code' => 45872,
'price' => 300,
'currency' => 'USD',
],
[
'code' => 45875,
'price' => 250,
'currency' => 'USD',
],
];
And my desired output is:
Array
(
[0] => Array
(
[code] => 29822
[price] => 150
[currency] => USD
)
[1] => Array
(
[code] => 24785
[price] => 120
[currency] => USD
)
[2] => Array
(
[code] => 45875
[price] => 250
[currency] => USD
)
[3] => Array
(
[code] => 45872
[price] => 300
[currency] => USD
)
)
I have done this task using loop but my curiosity is to know that have there any easy way to do this job?
My codes what I used:
$sorted_prop = [];
foreach($recommended_props as $code){
foreach($prop_array as $key=>$property){
if($property['code'] == $code){
$sorted_prop[] = $property;
unset($prop_array[$key]);
break;
}
}
}
Any suggestion will be appreciated. Thanks All.
Upvotes: 1
Views: 86
Reputation: 1947
usort
is what you need!
$recommended_props = [29822, 24785, 45875, 45872];
usort($prop_array, function($a, $b) use $recommended_props {
return strpos($recommended_props, $a['code']) > strpos($recommended_props, $b['code']);
});
The code has not been tested but it should give you a good idea on how to proceed. (Note that you may also need to handle the case where the code is not in the $recommended_props array
Upvotes: 0
Reputation: 212452
usort() is the function to use:
$recommended_props = [29822, 24785, 45875, 45872];
$prop_array = [
[
'code' => 24785,
'price' => 120,
'currency' => 'USD',
],
[
'code' => 29822,
'price' => 150,
'currency' => 'USD',
],
[
'code' => 45872,
'price' => 300,
'currency' => 'USD',
],
[
'code' => 45875,
'price' => 250,
'currency' => 'USD',
],
];
usort(
$prop_array,
function($a, $b) use ($recommended_props) {
return (array_search($a['code'], $recommended_props) < array_search($b['code'], $recommended_props)) ? -1 : 1;
}
);
var_dump($prop_array);
You could probably make it more efficient flipping $recommended_props
, and using it for access via the key in the callback
Upvotes: 1