1

Please help me!

JSON:

{
"1":{
"TchID":"G303992",
"TchData":{
           "TchID":"G303992",
           "TchNama":"G303992",
           "TchPassword":43511824
           }
},
"2":{
"TchID":"G141843",
"TchData":{
           "TchID":"G141843",
           "TchNama":"G141843",
           "TchPassword":22932450
}
}
}

How to update value in nested object from

"2":{
"TchID":"G141843",
"TchData":{
           "TchID":"G141843",
           "TchNama":"G141843",
           "TchPassword":22932450
}
}

to

"2":{
"TchID":"G141843",
"TchData":{
           "TchID":"G141843",
           "TchNama":"Alex J",
           "TchPassword":22932450
}
}

in php script?????

You see that i want to change "TchNama":"G141843" to "TchNama":"Alex J"

Here my code

<?php
$data = '{"1":{"TchID":"G303992","TchData":{"TchID":"G303992","TchNama":"G303992","TchPassword":43511824}},"2":{"TchID":"G141843","TchData":{"TchID":"G141843","TchNama":"G141843","TchPassword":22932450}}}';

$guru = json_decode($data);
foreach ($guru as $items){
if($items['TchID'] == 'G303992'){

// i dont know how to change $items['TchData']['TchNama'] = 'G141843' to 'Alex J'

$viewchange = json_encode($guru);
echo $viewchange;
}
}
?>
1
  • (Encoding the modified array back as JSON and outputting it belongs after the loop, of course.) Commented Jun 8, 2020 at 11:22

2 Answers 2

2

You can covert the json string to an array-object using json_encode($,TRUE).

Then you will be able to loop through the keys of the object if you obtain the keys by array_keys().

And then you can either use a separate variable to iterate through the main object properties and change that object, or directly access the main object and change it at the source, which is what I did below:

$data = '{"1":{"TchID":"G303992","TchData":{"TchID":"G303992","TchNama":"G303992","TchPassword":43511824}},
          "2":{"TchID":"G141843","TchData":{"TchID":"G141843","TchNama":"G141843","TchPassword":22932450}}}';

$guru = json_decode($data, true);

$keys = array_keys($guru);

foreach ($keys as $key) {
    if($guru[$key]['TchID'] == 'G303992'){
        $guru[$key]["TchNama"] = "Alex J";
    }
}

$viewchange = json_encode($guru);
echo $viewchange;
Sign up to request clarification or add additional context in comments.

1 Comment

@my0940 Are you sure? I tested it here: sandbox.onlinephpfunctions.com/code/…
1

Please try this.

$data = '{"1":{"TchID":"G303992","TchData":{"TchID":"G303992","TchNama":"G303992","TchPassword":43511824}},"2":{"TchID":"G141843","TchData":{"TchID":"G141843","TchNama":"G141843","TchPassword":22932450}}}';
$guru = json_decode($data);
var_dump($guru);
foreach ($guru as $items) {
    if ($items->TchID == 'G141843') {
        $items->TchData->TchNama = "Alex J";
    }
}
var_dump($guru);
$viewchange = json_encode($guru);
echo $viewchange;

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.