使用PHP按值排序json数组

时间:2017-04-01 06:47:48

标签: php json sorting

我正在尝试使用usort()对数组进行排序。但我的功能似乎不起作用。我希望按每个对象partners_order对它进行排序,例如$ myJson [0]然后单独$ myJson 1

使用$myJson = json_decode($jsonData);

解码Json数组

要排序的PHP函数如下所示。

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

由于此网站的限制,我无法在此发布数组。因此,我被迫使用第三方网站fiddle https://jsfiddle.net/z8s18c21/

有什么帮助吗?

1 个答案:

答案 0 :(得分:1)

我认为如果你使用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 ? -1 : 1;
  });
}

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

代码现已经过测试,因为您提供了数据对象。