从JSON解码中删除数组

时间:2013-05-30 22:01:15

标签: php arrays preg-replace json

这是我用来抓取和处理JSON输入的函数:

<?php
$json = "http://pastebin.com/raw.php?i=ihAapq30";
$cache_lastfm = 'BLAHBLAHDIR/'.sha1($json).'.json';

if(file_exists($cache_lastfm) && filemtime($cache_lastfm) > time() - 1000){
    // if a cache file newer than 1000 seconds exists, use it
    $data = json_decode(file_get_contents($cache_lastfm), true);
} else {
    $data = json_decode(file_get_contents($json), true);
    file_put_contents($cache_lastfm,json_encode($data));
}

$data = $data['recenttracks'];
foreach ($data['track'] as $track) {
    $artist = $track['artist']['#text'];
    $title = $track['name'];
    $url = $track['url'];
echo '<li><a href="', $url, '" title="', $title, '">', $artist, ' - ', $title, '</li></a>'; }
?>

它完美无缺..我的问题是,我怎样才能删除具有以下内容的“条目”:

        "@attr":{
           "nowplaying":"true"
        }

...“属性”?检查pastebin页面以了解我的意思:))

1 个答案:

答案 0 :(得分:2)

请试试这个:

<?php
    $data = $data['recenttracks'];

    $tracks=$data['track'];

    foreach ($tracks as $index=>$track) {
        if (isset($track['@attr'])) {
            unset($tracks[$index]);
        }
    }

    foreach ($tracks as $track) {
        $artist = $track['artist']['#text'];
        $title  = $track['name'];
        $url    = $track['url'];
        echo '<li><a href="', $url, '" title="', $title, '">', $artist, ' - ', $title, '</li></a>';
    }
?>