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;
}
}
?>
Cody Gray - on strike
  • 239,200
  • 50
  • 490
  • 574
my 0940
  • 35
  • 9
  • (Encoding the modified array back as JSON and outputting it belongs _after_ the loop, of course.) – CBroe Jun 08 '20 at 11:22

2 Answers2

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;
Ahmad
  • 12,336
  • 6
  • 48
  • 88
  • @my0940 Are you sure? I tested it here: http://sandbox.onlinephpfunctions.com/code/29dfca1d2c7c5d7916996c672ef513050b6abf5a – Ahmad Jun 08 '20 at 12:22
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;
Umair Khan
  • 1,684
  • 18
  • 34