Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add new key/value pair into JSON in PHP

Tags:

json

php

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"
    }
] 

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"
    }
]

So how can I do that in PHP?

like image 810
OussamaLord Avatar asked Oct 18 '13 10:10

OussamaLord


1 Answers

<?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);

?>
like image 197
Jenson M John Avatar answered Oct 10 '22 13:10

Jenson M John