【发布时间】:2015-04-23 16:35:27
【问题描述】:
我是 PHP 和 JSON 的新手,正在尝试将一些数据(我从 Instagram API 中获取)写入 json 文件。我知道我已经成功解码并在foreach() 循环中从 Instagram 抓取了数组,因为我可以将它们回显出来,但我似乎无法正确地将它们写入 json。当我这样做时,我只得到一个数组,而不是它们的集合......这是我的代码:
foreach($instagram_array['data'] as $key => $image){
$id = $image['id'];
$url = $image['images']['standard_resolution']['url'];
$date_shot = date('M d, Y', $image['created_time']);
$likes = $image['likes']['count'];
};
//I've tried wrapping this below in a foreach loop as well, but without success
$values = array(
'id' => $id,
'url' => $url,
'likes' => $likes,
'date_shot' => $date_shot,
);
file_put_contents('mydata.json', json_encode($values, JSON_FORCE_OBJECT)); // I wondered if force_object was the problem, but same result without it...
我得到的是这个,只有一次(循环中的最后一个):
{
id: "123_456",
url: "http://whatever.jpg",
likes: 5,
date_shot: "Jan 19, 2015"
}
当我希望得到(我认为)更像这样的东西(整个循环):
{
0: {
id: "123_456",
url: "http://whatever.jpg",
likes: 5,
date_shot: "Jan 19, 2015"
}
1: {
id: "123_457",
url: "http://whatever2.jpg",
likes: 10,
date_shot: "Jan 21, 2015"
}
2: {...}
}...
最终的目标是将这个 json 文件与其自身的更新版本合并,作为一个不断增长的文件,以防首先如何最好地写入 json...
【问题讨论】:
-
循环的每次迭代都会覆盖 vars 的值。
标签: php arrays json foreach instagram-api