[英]Why is PHP Foreach Loop only extracting last item in the element of JSON Array?
我正在从JSON文件中提取数据,并且除了一个项目外,获取所有项目都没有问题,因为它是JSON数组中的一个数组。
这是JSON数组的示例:
{
"items": [
{
"id": "12345",
"snippet": {
"publishedAt": "2015-07-25T02:43:39.000Z",
"channelTitle": "BuzzFeedVideo",
"tags": [
"celebrity",
"celebrities",
"seven",
"seven years",
"years",
"different",
"now",
"then",
"ariana grande",
"justin bieber",
"calvin harris",
"miley cyrus",
"abigail breslin",
"daniel radcliffe",
"neville longbottom",
"matthew lewis",
"buzzfeed",
"buzzfeedvideo",
"buzzfeedyellow",
"video"
],
"defaultAudioLanguage": "en"
},
"statistics": {
"viewCount": "700146",
"likeCount": "16847",
"dislikeCount": "596",
"favoriteCount": "0",
"commentCount": "1563"
}
}
]
}
我可以获取id,snippet:publishedAt,但是当涉及到标签时,我的foreach循环仅提取标签数组"video"
的最后一项。
这是我的foreach循环:
$tags = $videosResponse['items'][0]['snippet']['tags'];
foreach($tags as $tag):
$keywords = $tag;
echo $keywords;
endforeach;
如何获取JSON标签数组中从"celebrity"
到"video"
?
更新:
我想做的是使用file_put_contents用JSON数据更新php数组文件。
这是我正在使用的结构。
$tags = $videosResponse['items'][0]['snippet']['tags'];
foreach($tags as $tag):
$keywords = strtolower(replace_utf8_chars($tag));
$new_array_line = " '" . $id . "' => array\n\t(\n\t'datetime' => '" . $publishedAt . "',\n\t'title' => '" . addslashes($title) . "',\n\t'description' => '" . addslashes($description) . "',\n\t'channel title' => '" . addslashes($channelTitle) . "',\n\t'tags' => '" . $keywords . "',\n\t'duration' => '" . $duration . "',\n\t'viewCount' => '" . $viewCount . "',\n\t'likeCount' => '" . $likeCount . "',\n\t'commentCount' => '" . $commentCount . "',\n\t'url' => '" . $url . "'\n\t),";
endforeach;
然后数组pop和file put的内容代码位于$new_array_line
变量的下方。
if(!array_key_exists($id, $videoids)) {
$id_content = file($videoids_file); // Parse file into an array by newline
$id_data = array_pop($id_content);
if (trim($id_data) == ');?>') {
$id_content[] = "\n" . ' // ' . $_SERVER['REMOTE_ADDR'] . ' | ' . date('M j, y h:i:s A') . "\n"; // Echo debug line
$id_content[] = $new_array_line;
$id_content[] = "\n".$id_data;
file_put_contents($videoids_file, implode($id_content));
}
return array('title' => $title, 'description' => $description, 'channelTitle' => $channelTitle);
}
如果我在最后一部分之后结束foreach,则输出tag数组中的第一项,但是如果我在if语句之前结束foreach,则仅输出tags数组中的最后一项。
在执行if语句之前是否需要某种时间延迟?
$new_array_line =
需要替换为$new_array_line .=
否则在评估下一个标签值时,foreach循环将继续覆盖它,直到保留与“ video ”标签相关的最后一个值。
从来没有听说过endforeach ...
当JSON有效时,您应该能够使用以下命令访问数组:
$videosResponse['items'][0]['tags'];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.