在 PHP 中将新的键/值对添加到 JSON 中


Add new key/value pair into JSON in PHP

我有一个来自我的MySQL数据库的结果,我正在用PHP进行json编码,结果看起来像:

[
    {
        "id": "8488",
        "name": "Tenby",
        "area": "Area1"
    },
    {
        "id": "8489",
        "name": "Harbour",
        "area": "Area1"
    },
    {
        "id": "8490",
        "name": "Mobius",
        "area": "Area1"
    }
] 

我想做的是向该 JSON 添加新的键/值对,以便它:

[
    {
        "id": "8488",
        "name": "Tenby",
        "area": "Area1",
        "image": "1278.jpg"
    },
    {
        "id": "8489",
        "name": "Harbour",
        "area": "Area1",
        "image": "1279.jpg"
    },
    {
        "id": "8490",
        "name": "Mobius",
        "area": "Area1",
        "image": "1280.jpg"
    }
]

那么如何在 PHP 中做到这一点呢?

<?php
$data[0]['id']="8488";
$data[0]['name']="Tenby";
$data[0]['area']="Area1";
$data[1]['id']="8489";
$data[1]['name']="Harbour";
$data[1]['area']="Area1";
$data[2]['id']="8490";
$data[2]['name']="Mobius";
$data[2]['area']="Area1";
echo json_encode($data)."<br/>";
/*Add Image element (or whatever) into the array according to your needs*/
$data[0]['image']="1278.jpg";
$data[1]['image']="1279.jpg";
$data[2]['image']="1280.jpg";
echo json_encode($data);
?>

PHP对JSON不是很好。最好从JSON转换为数组来执行此操作 - @egig也建议这样做。

示例代码:

$temp = json_decode($json);
$temp[] = new data, whatever you want to add...;
$json = json_encode($temp);

希望这有帮助。

hu?

数据库查询的结果将是一个数组或一个对象...向该数据添加附加条目,仅在完成每个必要的数据操作后进行编码

替代方案,但笨拙(可怕):

  • json_decode,添加内容,json_encode
  • 将其他数据构建为字符串,例如str_replace JSON 字符串中"area": "Area1" "area": "Area1", "image": "1278.jpg"

但实际上:像json_encode这样的输出格式化只有在您确定将整个输出放在一起并发送出去后才应完成

也许从那时起情况发生了变化,但我知道这在当前阶段会起作用:-

所以这是 JSON 字符串:-

$strJSON = '[
  {
      "id": "8488",
      "name": "Tenby",
      "area": "Area1"
  },
  {
      "id": "8489",
      "name": "Harbour",
      "area": "Area1"
  },
  {
      "id": "8490",
      "name": "Mobius",
      "area": "Area1"
  }
]';

如果这仍然是一个字符串,那么我会将其转换为这样的对象:-

$json = json_decode( $strJSON );

现在它是对象格式,要添加我的"图像"键及其值,然后我会添加它们,如下所示:-

$json[0]->image = "1278.jpg";
$json[1]->image = "1279.jpg";
$json[2]->image = "1280.jpg";

因此,如果我在上面的代码之后添加下面的代码:-

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

然后我们应该在页面上看到它输出,如下所示:-

Array
(
    [0] => stdClass Object
        (
            [id] => 8488
            [name] => Tenby
            [area] => Area1
            [image] => 1278.jpg
        )
    [1] => stdClass Object
        (
            [id] => 8489
            [name] => Harbour
            [area] => Area1
            [image] => 1279.jpg
        )
    [2] => stdClass Object
        (
            [id] => 8490
            [name] => Mobius
            [area] => Area1
            [image] => 1280.jpg
        )
)

//$index = 数组中的某个值;

for($i=0;$i<count($index);$i++){
            $data[$i]->key = $index[$i];
        }
print $data;