1
<?php
$json = "http://pastebin.com/raw.php?i=e1Sw66C3";
$data = json_decode(file_get_contents($json), true);

$data = $data['recenttracks'];
$tracks=$data['track'];

 foreach ($tracks as $track) {
    $artist = $track['artist']['#text'];
    $title = $track['name'];
    $url = $track['url'];
    $image = array_reduce($track['image'], function ($image, array $i) { return $image ?: ($i['size'] == 'large' ? $i['#text'] : null); });
echo '<li><a rel="external nofollow" href="'.htmlentities($url, ENT_QUOTES, "UTF-8").'" title="', $title, '">', $artist, ' - ', $title, '</a></li>'; }
echo ($image);
?>

这个片段一直有效。现在我不知道为什么 BOOMecho ($image);什么也没输出。我无法弄清楚该功能有什么问题。其余代码工作正常(其他信息取自输入)。您可以通过转到 中的链接来检查输入file_get_contents

4

1 回答 1

0

正如我在评论中所写的那样,以前您的代码之所以有效,是因为元素 withsize = 'large'是最后一个,否则$image在每个循环中都会覆盖变量。你需要的是这样的

$json = "http://pastebin.com/raw.php?i=e1Sw66C3";
$data = json_decode(file_get_contents($json), true);

$data = $data['recenttracks'];
$tracks=$data['track'];
$images = array();

 foreach ($tracks as $track) {
    $artist = $track['artist']['#text'];
    $title = $track['name'];
    $url = $track['url'];
    if (isset($track['image']) && is_array($track['image']))
       foreach($track['image'] as $image)
          if (isset($image['size']) && $image['size'] == 'large' &&
              isset($image['#text']) && !empty($image['#text']))
             $images[] = $image['#text'];

    echo '<li><a rel="external nofollow" href="' . 
          htmlentities($url, ENT_QUOTES, "UTF-8") . '" title="', $title, '">',
          $artist, ' - ', $title, '</a></li>'; 
}
echo join("\n", $images);
于 2014-11-06T02:51:36.110 回答