Php 从JSON解码中删除数组
下面是我用来获取和处理JSON输入的函数:Php 从JSON解码中删除数组,php,arrays,preg-replace,json,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
<?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>'; }
?>
。。。“属性”?查看pastebin页面了解我的意思:)请尝试以下操作:
<?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>';
}
?>
谢谢您的回复!只有当条目具有“nowplaying”属性(在“@attr”下)时,我才需要删除该条目。如何使用此规范修改您的回复?:)检查更新,代码对我来说很好,我只是更改了测试的格式。哦,这是我的错。。我解释得很糟糕。我需要整个。。如果存在nowplaying(艺术家、唱片集名称、歌曲等),则要删除的阵列歌曲(在本例中)。检查更新,如果找到nowplaying
,则代码现在将删除整个歌曲。我猜现在只有一个正在播放
,如果我能再猜一次,它每次都是第一个元素。如果是这种情况,只需将数组向后移动一次。(这是第二个解决方案)这是我的代码更新,但我仍然得到了“nowplaying”对象:对于问题:如果nowplaying存在,它总是作为第一个元素(但它并不总是存在)。为什么不使用普通的unset($data['recenttracks']['@attr'])代码>,在进入循环之前?我在$data=$data['recenttracks']之前和之后添加了它;但结果是一样的(带有“nowplaying”的条目仍然存在)。。
<?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>';
}
?>