2017-06-19 92 views
2

我在一个名为info.json看起来像这样有一个JSON对象 - >添加JSON元多维JSON对象PHP

[ 
    { 
     "name": "level0", 
     "items": 
      [ 
       { 
        "name": "item1", 
        "type": "type1" 
       }, 
       { 
        "name": "item2", 
        "type": "type2" 
       } 

      ] 
    }, 
    { 
     "name": "Level1", 
     "items": 
      [ 
       { 
        "name": "item4", 
        "type": "type4" 
       }, 
       { 
        "name": "item5", 
        "type": "type5" 
       } 
      ] 
    }, 
    { 
     "name": "Level2", 
     "items": 
      [ 
       { 
        "name": "item6", 
        "type": "type6" 
       } 

      ] 
    } 
] 

和PHP脚本,看起来像这样 - >

<?php 

    $json_string = file_get_contents("info.json"); 
    $json = json_decode($json_string, true); 

    array_push($json[0]["items"], array("name" => "item3", "type" => "type3")); 
?> 

我想在这个数组中的“items”的第一个实例中插入第三个元素,这样当我打开JSON文件时,将会出现新的元素。我究竟做错了什么?任何意见,将不胜感激,谢谢。

+0

你用上面的代码得到的输出是什么? –

+0

这里有什么问题? –

+0

尽管$ json的值是,文件本身并没有改变。 – laroy

回答

1

后更改了$json数组,你需要将它保存到您的info.json文件与此,

file_put_contents("info.json", json_encode($json)); 
1

你的代码对我来说看起来很好。输出$json变量,你将能够看到你想要的结果。

print(json_encode($json, JSON_PRETTY_PRINT)); 

我做给你一个例子:https://eval.in/818486

希望这有助于:)

0

你好laroy你有没有合适的新的JSON编码字符串的文件,以便您的代码看起来像这样

<?php 

$json_string = file_get_contents("info.json"); 
$json = json_decode($json_string, true); 
array_push($json[0]["items"], array("name" => "item3", "type" => "type3")); 
$strNew = json_encode($json); 
file_put_contents("info.json", $strNew); 

?>

现在你可以检查的info.json文件。