Consider an array:
$arr = [
235 => [
"position" => 2,
10 => 1,
20 => 5,
235 => 2
],
456 => [
"position" => 1,
30 => 2,
20 => 1
]
];
Lets suppose we need to sort the 1st dimension based on the position key. What we can do is use the php’s uasort built-in method which will optimize the execution time of the script, we can do it like so:
uasort(<the array>, <callback>);
Replacing the values in the above uasort method:
function customSort($x, $y) {
if($x["position"] > $y["position"]) {
return 1;
} elseif ($x["position"] < $y["position"]) {
return -1;
}
return 0;
}
uasort($arr, "customSort");
or if your above or at php-7.0.0 then use the spaceship operator
function customSort($x, $y) {
return $x["position"] <=> $y["position"];
}
or if you’r at or above php-7.4.0, use the arrow function/short closure like so:
uasort($arr, fn($x, $y) => $x["position"] <=> $y["position"]);
The spaceship operator return 1 if the left side is greater than the right side, -1 if less than and 0 if the left side is equal to the right side. The uasort must return 1, -1 or 0. If anything else is returned the behavior of the function can be unexpected and may result in incorrect output.
While the uasort runs through the array if compares the values like so:
first loop: firstVal <=> secondVal
second loop: secondVal <=> thirdVal
third loop: thirdVal <=> fourthVal
and so on...
The uasort sorts the array in place which means you need not assign a variable to it. The final array will look like so:
$arr = [
456 => [
"position" => 1,
30 => 2,
20 => 1
],
235 => [
"position" => 2,
10 => 1,
20 => 5,
235 => 2
]
];
Leave a Reply