phpjsonparsinggrandchild

Need help parsing JSON decoded grandchildren with PHP


foreach($response_2['items'] as $item) {
$item['track']['name'] = (array)$item['track']['name'];
foreach($item['track']['name'] as $key => $value) {
    echo $value . "<br />";
}
$item['track']['artists']['name'] = (array)$item['track']['artists']['name'];
foreach($item['track']['artists']['name'] as $key => $value) {
    echo $value . "<br />";
} 
$item['track']['duration_ms'] = (array)$item['track']['duration_ms'];
foreach($item['track']['duration_ms'] as $key => $value) {
    echo $value . "<br />";
    } 
}

...to parse this response: http://pastebin.com/uxBF3Kxe# (after I've decoded it).

All the values for ['track']['name'] and ['track']['duration_ms'] are echoed correctly, but nothing is echoed for ['track']['artists']['name'].

What am I doing wrong here?

Thanks!


Solution

  • ['track']['artists'] is array :)

    Try this ;)

    foreach($item['track']['artists'] as $key => $value) {
        echo $value['name'] . "<br />";
    }
    

    Btw... This is better solution ;)

    $response_2 = json_decode($json, true);
    
    foreach($response_2['items'] as $item) {
        echo $item['track']['name'] . "<br />";
    
        foreach($item['track']['artists'] as $key => $value) {
            echo $value['name'] . "<br />";
        }
    
        echo $item['track']['duration_ms'] . "<br />";
    }
    

    /** Added separator */

    $response_2 = json_decode($json, true);
    
    foreach($response_2['items'] as $item) {
        echo $item['track']['name'] . "<br />";
    
        echo implode(',', array_map(
                function ($value) {
                    return $value['name'];
                },
                $item['track']['artists']
            )
        );
    
        echo "<br />";
    
        echo $item['track']['duration_ms'] . "<br />";
    }