如何使用 PHP 向 JSON 对象添加元素?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34633272/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 00:08:15  来源:igfitidea点击:

How to add element to JSON object using PHP?

phpjson

提问by sdfgg45

I have this JSON array, and i want to add another value to it using PHP.

我有这个 JSON 数组,我想使用 PHP 向它添加另一个值。

What would be the easiest way to add a ID and Name to this array using PHP.

使用 PHP 向该数组添加 ID 和名称的最简单方法是什么。

 [
   {
      "id":1,
      "name":"Charlie"
   },
   {
      "id":2,
      "name":"Brown"
   },
   {
      "id":3,
      "name":"Subitem",
      "children":[
         {
            "id":4,
            "name":"Alfa"
         },
         {
            "id":5,
            "name":"Bravo"
         }
      ]
   },
   {
      "id":8,
      "name":"James"
   }
]

回答by Pupil

Simply, decode it using json_decode()

简单地,使用json_decode()对其进行解码

And append array to resulting array.

并将数组附加到结果数组。

Again encode it using json_encode()

再次使用json_encode()对其进行编码

Complete code:

完整代码:

<?php
$arr = '[
   {
      "id":1,
      "name":"Charlie"
   },
   {
      "id":2,
      "name":"Brown"
   },
   {
      "id":3,
      "name":"Subitem",
      "children":[
         {
            "id":4,
            "name":"Alfa"
         },
         {
            "id":5,
            "name":"Bravo"
         }
      ]
   },
   {
      "id":8,
      "name":"James"
   }
]';
$arr = json_decode($arr, TRUE);
$arr[] = ['id' => '9999', 'name' => 'Name'];
$json = json_encode($arr);

echo '<pre>';
print_r($json);
echo '</pre>';