Skip to content
Advertisement

Sort json array by value using PHP

I am trying to sort the array using usort().But my function does not seem to work. I want to sort it by partners_order of each object i.e, $myJson[0] and then $myJson1 separately

The Json array is decoded using $myJson = json_decode($jsonData);

PHP function to sort is written below.

usort($myJson, function($a, $b) {        
return $a->partners->partners_order < $b->partners->partners_order ? -1 : 1; 
});

Due to restrictions in this site, I cant post the array here. Hence I am forced to use 3rd party site fiddle https://jsfiddle.net/z8s18c21/

any help please ?

Advertisement

Answer

I think it might work if you loop over your objects with foreach.

$myJson = '[
{
    "title":"1st Inning",
    "inning_order":0,
    "partners":[
        {"partners_order":3,"partner_1":{"id":1927312,"runs":31},"partner_2":{"id":1462508,"runs":32}},
        {"partners_order":1,"partner_1":{"id":1927311,"runs":11},"partner_2":{"id":1462508,"runs":12}},
        {"partners_order":2,"partner_1":{"id":1927311,"runs":21},"partner_2":{"id":1462507,"runs":22}}
    ]
},
{
    "title":"2nd Inning",
    "inning_order":1,
    "partners":[
        {"partners_order":2,"partner_1":{"id":927312,"runs":21},"partner_2":{"id":462508,"runs":22}},
        {"partners_order":1,"partner_1":{"id":927311,"runs":11},"partner_2":{"id":462508,"runs":21}},
        {"partners_order":3,"partner_1":{"id":927311,"runs":31},"partner_2":{"id":462507,"runs":32}}
    ]

}
]';

$read_json = json_decode($myJson);

foreach ($read_json as $myJson1) {
  usort($myJson1->partners,function($a, $b) {
    return $a->partners_order <=> $b->partners_order;
  });
}

echo '<pre>';
print_r($read_json);
echo '</pre>';

Code has now been tested, because you provided the data objects.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement