Json_decode:从具有相同名称的对象列表中获取特定条目


json_decode: get specific entry out of a list of objects with same name

这是我的输入JSON

    {
        "artist":{
           "#text":"Radical Face",
           "mbid":"6c25514f-1f14-4106-a142-be95ba11f117"
        },
        "name":"Let the River In",
        "streamable":"1",
        "mbid":"fd4c8c63-2cb4-4282-87cd-a75a332f64ba",
        "album":{
           "#text":"Ghost",
           "mbid":"c5c64ec1-3271-4461-92ea-3727cdc71995"
        },
        "url":"http:'/'/www.last.fm'/music'/Radical+Face'/_'/Let+the+River+In",
        "image":[
           {
              "#text":"http:'/'/userserve-ak.last.fm'/serve'/34s'/3996573.jpg",
              "size":"small"
           },
           {
              "#text":"http:'/'/userserve-ak.last.fm'/serve'/64s'/3996573.jpg",
              "size":"medium"
           },
           {
              "#text":"http:'/'/userserve-ak.last.fm'/serve'/126'/3996573.jpg",
              "size":"large"
           },
           {
              "#text":"http:'/'/userserve-ak.last.fm'/serve'/300x300'/3996573.jpg",
              "size":"extralarge"
           }
        ],
        "date":{
           "#text":"5 Jun 2013, 17:57",
           "uts":"1370455055"
        }
     },

我用

从中提取数据
$tracks=$data['track'];
foreach ($tracks as $track) {
$artist = $track['artist']['#text'];
$title = $track['name'];
$url = $track['url'];
...
}

…这工作。现在我的问题是:我怎么能得到中等缩略图,因为它们都在'image'->'#text'下?每个都有另一个条目(与'#text'一起),它指定了大小('image'->'size'),但我怎么能得到中等拇指url?

$image = null;
foreach ($track['image'] as $i) {
    if ($i['size'] == 'medium') {
        $image = $i['#text'];
        break;
    }
}

或:

$image = array_reduce($track['image'], function ($image, array $i) { return $image ?: ($i['size'] == 'medium' ? $i['#text'] : null); });

或:

$image = array_filter($track['image'], function ($image) { return $image['size'] == 'medium'; });
$image = isset($image[0]['#text']) ? $image[0]['#text'] : null;

或:

$track['image'] = array_combine(
    array_map(function ($i) { return $i['size']; }, $track['image']),
    array_map(function ($i) { return $i['#text']; }, $track['image'])
);
$image = $track['image']['medium'];

等。等。

在foreach循环中,对image字段

执行另一次foreach操作。
$thumbs = $track['image']
$medium = '';
foreach ($thumbs as $thumb) {
  if ($thumb['size'] == 'medium')
  {
    $medium = $thumb['#text']
    break;
  }
}