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文件。