I have some json objects which look like this:
{
"name": "Jan",
"contracthours": 20,
"overtimehours": 5,
"extrahours": 4,
"category": "Cleaning",
"bgcolor": "#2ECC40",
"textcolor": "#ffffff"
}
The key category can have 6 different values: Manager, Assistant, Frontoffice, Flexworker, Cleaning, & Other.
How can I sort the array of json files in this order?
- Manager
- Assistant
- Flexworker
- Cleaning
- Frontoffice
- Other
This is the code I have so far:
$s_files = glob("data/staff/*.json"); // all staff json files
foreach($s_files as $s_file) {
$s_array[] = json_decode(file_get_contents($s_file), true);
}
foreach($s_array as $key => $val) {
echo $val['name'].'<br />';
echo $val['category'].'<br />'; // Manager should be first, Assistant second and so on...
...
>Solution :
You would do that with usort() and feed in a custom sorting order with use. Sample code:
// Here is your sorting order:
$sorts = [
'Manager' => 1,
'Assistant' => 2,
'Flexworker' => 3,
'Cleaning' => 4,
'Frontoffice' => 5,
'Other' => 6
];
// This is representative data:
$employees = [
['name' => 'Jan', 'category' => 'Cleaning'],
['name' => 'Jane', 'category' => 'Manager'],
['name' => 'Jano', 'category' => 'Assistant'],
['name' => 'Janu', 'category' => 'Assistant'],
['name' => 'Janx', 'category' => 'Flexworker'],
['name' => 'Janny', 'category' => 'Frontoffice'],
['name' => 'Jando', 'category' => 'Other'],
['name' => 'Jansan', 'category' => 'Manager'],
];
// Here we lookup the sorting values for each category:
usort($employees, function($a, $b) use ($sorts) {
return $sorts[$a['category']] <=> $sorts[$b['category']];
});
Read the comments to understand. Then see the sample code in action.
You’d want to have a check to ensure all employees fit into your assumed categories (before the sort routine); and assign "Other" (or throw an exception) wherever there’s an unexpected role.