Foreach在带有JSON的数组中循环

时间:2015-01-27 20:41:43

标签: php json

我有这个PHP代码

<?php
    $json = file_get_contents('comments.json');
    $decode = json_decode($json);
    $name = $_POST['name'];
    $email = $_POST['email'];
    $comment = $_POST['comment'];
    foreach($decode->comments as $key)
    {
        var_dump(array(
            $key->name,
            $key->email,
            $key->comment
        ));
    }
    $decode->comments = array(array('name'=>$name, 'email'=>$email, 'comment'=>$comment));
    $encode = json_encode($decode,JSON_FORCE_OBJECT);
    file_put_contents('comments.json',$encode);
?>

它有点工作,它将JSON文件中的当前内容设置为它在这段PHP代码中告知的内容。而不是这个,我希望PHP代码添加到已经存在的JSON。

这是JSON文件。

  {
        "comments": {
            "0": {
                "name": "123",
                "email": "123",
                "comment": "123"
            }
        }
  }

1 个答案:

答案 0 :(得分:1)

传递布尔值true,以便获得关联数组而不是基于对象的解码:

$json = file_get_contents('comments.json', true);

将所有OOP引用更改为关联数组样式:

foreach($decode['comments'] as $key)
{
    var_dump($key); // Declaring a whole new array isn't really needed here
}

使用[]语法附加到已解码的JSON数组:

$decode['comments'][] = array(
    'name' => $name,
    'email' => $email,
    'comment' => $comment,
);

重新编码并返回生成的JSON:

$encode = json_encode($decode, JSON_FORCE_OBJECT);
file_put_contents('comments.json',$encode);