Skip to content

Instantly share code, notes, and snippets.

@fuongz
Created April 12, 2023 09:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fuongz/48bed323d3bcfe7f2403d35db67655cf to your computer and use it in GitHub Desktop.
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)
<?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