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

时间:2013-06-05 18:35:56

标签: php arrays json

这是我的输入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'];
...
}

......哪个工作。现在我的问题是:我怎样才能获得中等缩略图,因为它们都在'图像'下 - >'#text'?每个人都有另一个条目(连同'#text'),它指定了大小('image' - >'size'),但我怎样才能获得中等拇指网址?

2 个答案:

答案 0 :(得分:1)

$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'];

等。等

答案 1 :(得分:1)

在你的foreach循环中,在图像区域上做另一个foreach

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