为什么PHP Foreach循环只提取JSON数组元素中的最后一项?


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: publishhedat,但是当涉及到标记时,只有标记数组"video"中的最后一项被我的foreach循环提取。

这是我的foreach循环:
$tags = $videosResponse['items'][0]['snippet']['tags'];
foreach($tags as $tag):
    $keywords = $tag;
    echo $keywords;
endforeach;

如何获得JSON标签数组内的所有项目从"celebrity""video" ?

更新:

我要做的是更新一个php数组文件与JSON数据使用file_put_contents。

这是我使用的结构。

    $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和文件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,则输出标签数组中的第一项,但如果在If语句之前结束foreach,则只输出标签数组中的最后一项。

在if语句执行之前我需要某种时间延迟吗?

$new_array_line =需要被$new_array_line .=取代,否则foreach循环将在计算下一个标签值时继续覆盖它,直到保留与'video'标签相关的最后一个。

从未听说过endforeach…当JSON有效时,您应该能够使用

访问数组:
$videosResponse['items'][0]['tags'];