【问题标题】:write the results of foreach loop to json with php用php将foreach循环的结果写入json
【发布时间】: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


【解决方案1】:

您的问题似乎是您正在创建单个数组并将它们写入文件,而不是创建一个大的“数组数组”然后将其写入文件。

试试这一行:

$values[] = ...

$values 后面的方括号表示 $values 将成为一个多维数组。

它应该被移到你的 foreach 循环中,所以完整的代码现在看起来像这样:

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'];

    $values[] = array(
        'id' => $id,
        'url' => $url,
        'likes' => $likes,
        'date_shot' => $date_shot,
    );
);

file_put_contents('mydata.json', json_encode($values, JSON_FORCE_OBJECT));

【讨论】:

  • 工作!!谢谢@jones!
【解决方案2】:

您需要在每次迭代时将其推入 $arr 中的 $values

$arr = array();
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'];
    $values = array(
    'id' => $id,
    'url' => $url,
    'likes' => $likes,
    'date_shot' => $date_shot,
    );
    array_push($arr, $values); 
    };

    file_put_contents('mydata.json', json_encode($arr, JSON_FORCE_OBJECT)); 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-09-25
    • 1970-01-01
    • 2015-09-18
    • 2018-05-14
    • 2013-04-26
    • 2022-11-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多