[英]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.