1

How can i update the following JSON object dynamically using php?

this my json.

 {
    "1":
        {
            "value0":
                    {
                        "id":0,
                        "status":0,
                        "quantity":"110"
                    },
            "value1":
                    {
                        "id":1,
                        "status":1,
                        "quantity":"120"
                    }
        }
    "2":
        {
            value0":
                    {
                        "id":0,
                        "status":0,
                        "quantity":"132"
                    },
            "value1":
                    {
                        "id":1,
                        "status":1,
                        "quantity":"123"
                    },
        }
}

I want to change the status of value0 from key 1, to 1. How can I acheive this?

5
  • Convert JSON to array by using json_decode. Make the update in the array. Then convert the array into JSON by using json_encode. Commented May 22, 2017 at 7:14
  • $new_data = json_decode($data,true); $new_data[1]["value0"]["status"]=1; $data = json_encode($new_data); echo $data; Commented May 22, 2017 at 7:17
  • Oh thank you @manian, but when I tried json_endcode, my json changed to {"1":{"value0":{"status":1}}}. Commented May 22, 2017 at 7:19
  • sorry check my below answer .it will work as you expected Commented May 22, 2017 at 7:20
  • @JYoThI oh thanks, i really it works. Commented May 22, 2017 at 7:24

1 Answer 1

7

use json_decode() and json_enocde()

$data = json_decode($data,true);  
$data["1"]["value0"]["status"]=1;   
$data = json_encode($data);
echo $data;
Sign up to request clarification or add additional context in comments.

1 Comment

shouldn't it be ["1"] instead of [1] since its an assoc array and [1] would trigger second array element, which is key "2"?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.