0

这是我的输入 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'),但我怎样才能获得中等拇指网址?

4

2 回答 2

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

等等等等

于 2013-06-05T18:55:52.250 回答
1

在您的 foreach 循环中,在图像字段上执行另一个 foreach

$thumbs = $track['image']
$medium = '';
foreach ($thumbs as $thumb) {
  if ($thumb['size'] == 'medium')
  {
    $medium = $thumb['#text']
    break;
  }
}
于 2013-06-05T18:56:57.640 回答