【发布时间】:2017-10-15 08:37:56
【问题描述】:
我有一些解码的 json 数据,我想根据子值按特定顺序排序。解码后的json文件结构如下:
Array
(
[location] => Array
(
[id] => 10215235726
[title] => demo title
[media] => Array
(
[nodes] => Array
(
[0] => Array
(
[id] => 15129696952092
[thumbnail_src] => thumb_15131.jpg
[is_video] => 1
[code] => BTg35sbvdfc
[date] => 1494577207
[display_src] => image_15131.jpg
[video_views] => 318
[caption] => Batman
[comments] => Array
(
[count] => 2
)
[likes] => Array
(
[count] => 87
)
)
[1] => Array
(
[comments_disabled] =>
[id] => 47484867964790738
[thumbnail_src] => thumb_11536.jpg
[is_video] =>
[code] => BTmSAQghufS
[date] => 1493745672
[display_src] => image_11536.jpg
[caption] => Aquaman
[comments] => Array
(
[count] => 2
)
[likes] => Array
(
[count] => 73
)
)
etc...
我使用以下方法输出值没有问题:
$json = json_decode(file_get_contents("http://www.linktojson.com"), true);
foreach($json['location']['media']['nodes'] as $value) {
echo $value['display_src'];
}
但现在我想根据喜欢 ([count]) 对输出进行排序。我已经尝试了found in answers here 的几种方法,但我似乎无法以适合我的方式应用他们的解决方案。现在我正在看这个进行排序:
function custom_sort($a, $b) {
return $a['count'] - $b['count'];
}
usort($json, 'custom_sort');
这会抛出 usort() 期望参数 1 是数组,给定 null,而且还有两个 count 孩子(cmets 和喜欢),因此它可能无法正常工作。
我对使用这些类型的数组还很陌生,因此我们将不胜感激。
【问题讨论】:
-
那么还有什么不清楚的地方?
$data_array不是数组。 -
@u_mulder 抱歉,我的复制和粘贴错误。
标签: php arrays json sorting multidimensional-array