值对添加到JSON中

值对添加到JSON中

本文介绍了在PHP中将新的键/值对添加到JSON中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从MySQL数据库得到的结果是我使用PHP进行json编码,结果看起来像:

I have a result from my MySQL DB that I'm json encoding in PHP, the result looks like:

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

我想做的是向该JSON添加一个新的键/值对,使其成为:

What I would like to do is to add a new key/value pair to that JSON so that it will be :

[
    {
        "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中做到这一点?

So how can I do that in 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中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 23:20