Search code examples
phparraysjsonarray-reduce

json_decode: array_reduce stopped working


<?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);
?>

This snippet has always worked. Now I don't know why BOOM echo ($image); outputs nothing. I can't figure out what's wrong with that function. The rest of the code works fine (the other info taken from the input). You can check the input by going to the link in file_get_contents.


Solution

  • As I wrote in comments, previously your code was working only because element with size = 'large' was the last one, otherwise variable $image is overwritten at every loop. What you need is something like this

    $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);