Php 如何按顺序检索json数据

Php 如何按顺序检索json数据,php,json,Php,Json,我有如下简单的json结果 { "code": 200, "image": "https://example.com/image.jpg", "result": [ { "url": "https://example.com/1", "label": "MP4" }, { "url": "https://example.com/2", "label": "FLV" }, { "url"

我有如下简单的json结果

{
  "code": 200,
  "image": "https://example.com/image.jpg",
  "result": [
    {
      "url": "https://example.com/1",
      "label": "MP4"
    },
    {
      "url": "https://example.com/2",
      "label": "FLV"
    },
    {
      "url": "https://example.com/3",
      "label": "MP3"
    },
    {
      "url": "https://example.com/4",
      "label": "AVI"
    },
    {
      "url": "https://example.com/5",
      "label": "WMV"
    }
  ]
}
正如你所看到的,有这么多不同的标签路径,有时标签的顺序与上面的不同,它总是在变化(随机),我试图获得MP3标签部分,但不能。 我的问题是,如何获取带有MP3标签的json序列

我试过下面的脚本

$uri = json_decode(file_get_contents('https://example.com/json.json'),TRUE);
echo $uri['result'][2]['url'];
但如上所述,MP3标签的位置总是在变化,有没有办法克服它?

尝试以下代码:

$nodesWithMp3Labels = array_map(function($a) {
    if (strtolower($a["label"]) == "mp3") {
        return $a;
    }
}, $uri['result']);
阅读更多关于 使用
array\u map
,如果标签不是mp3,则会有一些空白值

另一个使用简单foreach循环的解决方案:

$nodesWithMp3Labels = [];

foreach ($uri['result'] as $a) {
    if (strtolower($a["label"]) == "mp3") {
        $nodesWithMp3Labels[] = $a;
    }
}

您应该使用
array\u filter
获得MP3标签的所有结果:

$uri = json_decode(file_get_contents('https://example.com/json.json'), true);

$mp3 = array_filter($uri['result'], function($item) {
    return $item['label'] === 'MP3';
})

迭代
结果
并检查
标签
值。一个简单的foreach和if语句就足够了Hanks ghost,它的工作区您将收到带有空值的数组,其中
标签
不是“mp3”。