kenny45
kenny45

Reputation: 31

add data to json (php)

can someone please help me to add data to following json.

$temp='{
  "custId": 123,
  "data": [
    {
      "code": "abc1"
    },
    {
      "code": "abc2"
    }
  ],
  "id": 102
}';

data to be added

$data1='{
      "code": "abc3"
    }';

Desired result

$temp='{
  "custId": 123,
  "data": [
    {
      "code": "abc1"
    },
    {
      "code": "abc2"
    },
    {
      "code": "abc3"
    }
  ],
  "id": 10
}';

I can append data to $temp, but can someone please help to add data to specific position with php. Thank you in advance. (I've tried json_decode($temp, true) and then finding the location where data1 is to be added but failed).

Upvotes: 1

Views: 1052

Answers (4)

ToBe
ToBe

Reputation: 2681

You can convert your data to a normal PHP array:

$array = json_decode($temp, true);

then just add or change anything you want:

$array["data"][] = array(["code"] => "abc3");

and re-encode to json:

$temp = json_encode($array);// encode to json

http://php.net/manual/en/function.json-decode.php

Upvotes: 3

Ares Draguna
Ares Draguna

Reputation: 1662

first, you need to convert the JSON into PHP array like this:

$array = json_decode($temp, true);

Then, it's as simple as:

$array['data']['code'] = 'abc3';

If the string that you want to add is still a JSON, you have to convert that one in an array as well so:

$arr_to_add = json_decode($data1, true);
$array['data'][] = $arr_to_add;

In the end, of course, encode again like this:

$final_json = json_encode($array);

Hope this helps! :D

Upvotes: 1

Dinesh
Dinesh

Reputation: 4110

you can try this:

<?php
$temp='{
  "custId": 123,
  "data": [
    {
      "code": "abc1"
    },
    {
      "code": "abc2"
    }
  ],
  "id": 102
}';
$data1='{
      "code": "abc3"
    }';
$jarr=json_decode($temp,true);
$appArr=json_decode($data1,true);
$desire=array_merge($jarr,$appArr);
//print_r($desire);
echo json_encode($desire);

Upvotes: 0

jherran
jherran

Reputation: 3367

  1. First you need to decode the json with json_decode. This returns a PHP variable.
  2. Add desired values.
  3. Use json_encode to get the json with new values. Returns a string containing the JSON.

Upvotes: 0

Related Questions