<?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);
?>
此代码段始终有效。现在我不知道为什么BOOM echo ($image);
什么都没输出。
我无法弄清楚这个功能有什么问题。其余代码工作正常(从输入中获取的其他信息)。您可以转到file_get_contents
中的链接检查输入。
答案 0 :(得分:0)
正如我在评论中所写,之前您的代码只是因为size = '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);