I have a known hierarchy of the organization units, by descending order:
$hierarchy = [
"a" => "organization",
"b" => "company",
"c" => "group",
"d" => "unit",
"e" => "sub_unit",
"f" => "team"
];
I am then given an input key-value array which can consist of any of the units, but not necessarily all of them, and not always in the correct order:
$array = [
"team" => "team1",
"organization" => "organization1",
"group" => "group1"
];
I want to sort it in the correct order, so for the example input array above, the result should be:
$array = [
"organization" => "organization1",
"group" => "group1"
"team" => "team1"
];
The way I did it seem too complicated for what it's supposed to do, so maybe there is a better/more efficient way:
public function sort_custom(&$array)
{
// set the known hierarchy ordered alphabetically by the keys
$hierarchy = [
"a" => "organization",
"b" => "company",
"c" => "group",
"d" => "unit",
"e" => "sub_unit",
"f" => "team"
];
// fill temp array with the key-value pair from the matching input array
$tmp_array = [];
foreach ($array as $key => $value) {
$match = array_search($key, $hierarchy);
$tmp_array[$match] = $key;
}
// sort the temp array
ksort($tmp_array);
// assign the values from the original array to the temp array
foreach ($tmp_array as $key => $val) {
$tmp_array[$val] = $array[$val];
unset($tmp_array[$key]);
}
// finally copy the sorted temp array to the original array
$array = $tmp_array;
}