There are two "styles" for ordering your Rates
subarrays in ascending order while preserving keys. The best tool for this job is uasort() because it allows you to perform a customized sort on the array that it is fed. The a
in uasort()
means "preserve the original keys".
The "magic" of the "user-defined sort" is in the second parameter -- a function call. No matter what function you decide to call, uasort()
will be delivering values in sets of two to the function for comparison (I am naming these values $a
and $b
). How you compare these two variables (and in what order you compare them) will determine the outcome of the sort.
I will be using the modern php "spaceship operator" for comparisons, but you may elect to use an older / more verbose set of "greater than, less than, equal to" conditions.
The first method "modifies by reference" with the &
symbol (instead of processing a copy of the array in the foreach loop, and the second method simply overwrites the original array on each iteration by referencing the necessary keys.
Method #1: "modify by reference"
foreach($array as &$subarray){ // modify $subarray by reference using &
uasort($subarray['Rates'],function($a,$b){
return $a['Price']<=>$b['Price']; // $b<=>$a would mean DESC order
});
}
Method #2: "iterative overwrite"
foreach($array as $key=>$subarray){ // iterate
$rates=$subarray['Rates']; // isolate the Rates subarray
uasort($rates,function($a,$b){ // sort the Rates subarray
return $a['Price']<=>$b['Price']; // ascending order
});
$array[$key]['Rates']=$rates; // overwrite the original array
}
To clarify a point that is specific to this case, you should NOT use array_multisort() because it will re-index your Rates
subarray (overwrite the original numeric keys starting from zero). For cases when you have associative keys -- go for it... just not this time.
DON'T USE THIS METHOD FOR YOUR CASE:
foreach($array as &$subarray){ // modify $subarray by reference using &
array_multisort(array_column($subarray['Rates'],'Price'),$subarray['Rates']);
}
NOR THIS ONE:
foreach($array as $key=>$subarray){ // iterate and overwrite
$rates=$subarray['Rates'];
array_multisort(array_column($rates,'Price'),$rates);
$array[$key]['Rates']=$rates;
}
Here is a demo page that has all four methods set up so that you can run them and see the output for yourself: Demo Link