Created
April 12, 2023 09:59
-
-
Save fuongz/48bed323d3bcfe7f2403d35db67655cf to your computer and use it in GitHub Desktop.
Order an array of objects based on another array order (fork from: https://gist.github.com/ecarter/1423674)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$arrayA = [ | |
[ | |
"status" => "Wait", | |
"id" => 1 | |
], | |
[ | |
"status" => "Approve", | |
"id" => 2 | |
], | |
[ | |
"status" => "Quote", | |
"id" => 3 | |
], | |
]; | |
$order = ["Quote", "Wait", "Approve"]; | |
function sortS($arr, $order, $key) { | |
$b = $arr; | |
usort($b, function ($a, $b) use ($key, $order) { | |
$A = $a[$key]; | |
$B = $b[$key]; | |
if (array_search($A, $order) > array_search($B, $order)) { | |
return 1; | |
} else { | |
return -1; | |
} | |
}); | |
return $b; | |
} | |
var_dump(sortS($arrayA, $order, 'status')); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment