0

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 ?

4
  • you can use eval.in for PHP , jsfiddle is for Javascript testing not php Commented Apr 1, 2017 at 6:51
  • Within $a->partners->partners_order the partners bit is an array. You have to use a key. We cannot answer your question because it is unclear how the sorting should be done. Commented Apr 1, 2017 at 6:54
  • @KIKOSoftware, Q updated. I want to sort it by partners_order of each object i.e, $myJson[0] and then $myJson[1] separately Commented Apr 1, 2017 at 7:05
  • please provide a testable php array or even valid json; Commented Apr 1, 2017 at 8:07

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

0

You may be referencing your array incorrectly. Try this:

$myJson = json_decode($jsonData, true);

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.