Sorting alphabetically an object returned by json_decode()

Viewed 32

I'm having trouble sorting alphabetically an object returned by the json_decode function in PHP.

The object I've got is as follows:

object(stdClass)#9263 (1) {
  ["Activities"]=>
  array(91) {
    [0]=>
    object(stdClass)#6116 (3) {
      ["Code"]=>
      string(1) "5"
      ["NameFr"]=>
      string(16) "Droit ju"
      ["NameNl"]=>
      string(18) "Ger recht"
    }
    [1]=>
    object(stdClass)#8582 (3) {
      ["Code"]=>
      string(1) "1"
      ["NameFr"]=>
      string(19) "Droit per"
      ["NameNl"]=>
      string(13) "Pers recht"
    }
    [2]=>
    object(stdClass)#8598 (3) {
      ["Code"]=>
      string(5) "2"
      ["NameFr"]=>
      string(11) "Droit ca"
      ["NameNl"]=>
      string(14) "Ca recht"
    }
...

I need to sort it using the "NameFr" property, alphabetically.

1 Answers

try usort

<?php

$data = ' 
{
   "Activities": [
     {
       "Code": "5",
       "NameFr": "Droit ju",
       "NameNl": "Ger recht"
     },
     {
       "Code": "1",
       "NameFr": "Droit per",
       "NameNl": "Pers recht"
     },
     {
       "Code": "2",
       "NameFr": "Droit ca",
       "NameNl": "Ca recht"
     }
   ]
}';

$data = json_decode($data, true);

usort($data["Activities"], function($a, $b) {
    return $a['NameFr'] <=> $b['NameFr'];
});

print_r($data);
Related