Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how to sort a json array by key value

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?

  1. Manager
  2. Assistant
  3. Flexworker
  4. Cleaning
  5. Frontoffice
  6. Other

This is the code I have so far:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

$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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading