0

This is the JSON

{
"table-name": "Kiwi",
"created-on": "November 20, 2021",
"columns": {
    "Info": {
        "type": "longtext",
        "extra": ""
    },
    "Status": {
        "type": "droplist",
        "extra": ""
    },
    "Task": {
        "type": "text",
        "extra": ""
    }
},
"data": [
    {
        "Name": "Team Reports",
        "Info": "Submitting marketing materials reports",
        "Status": "Completed"
    },
    {
        "Name": "Fabia HR",
        "Info": "Brian asking for a report",
        "Status": "Pending"
    },
    {
        "Name": "Fabia",
        "Info": "Meeting with CEO @cafe 9:00",
        "Status": "Cancelled"
    }
]

}

And I was trying to achieve to rename the "Info" into "Description" without losing its value and array position. I'm not very familiar with array_replace , that seems my code is not working. Please share some codes, it will be much appreciated.

Here my PHP code I tried

<?PHP

  $jsn = file_get_contents('./test.json');
  $arr = json_decode($jsn, true);

  $newArray= [];

  foreach($arr['data'] as $row){
  $row['Description'] = $row['Info'];
  array_push($newArray, $row);
  }
   
  //print_r($newArray);
  array_replace($arr['data'],$newArray);



 echo json_encode($arr, JSON_PRETTY_PRINT);

Thank you so much for your attention and advance help. It will really gonna save me some time. Noob here and I'm still learning things about PHP and JSON

Maharlikan
  • 63
  • 7
  • `$row['Description']` would be a value of the key `Description` in the array which is undefined, you need to change the key, most likely by unsetting `Info` and then creating `Description`. – Jaquarh Jan 14 '22 at 11:43
  • @Jaquarh this is not _read_ access, they are _assigning_ a value to `$row['Description']` there. – CBroe Jan 14 '22 at 11:44
  • I was too confused reading the question to see that, my bad. Now I just see `Info` is never un-set and the OP's issue with it probably not being in the "same place". @CBroe – Jaquarh Jan 14 '22 at 11:46
  • I don't see what you want with `array_replace` here? _"array_replace() replaces the values of array with values having the same keys in each of the following arrays."_ - how would that be helpful, the key to put the new value under would have to already exist, and it won't remove the "old" `info` key either. – CBroe Jan 14 '22 at 11:46
  • 1
    [Maybe this will help?](https://stackoverflow.com/questions/240660/in-php-how-do-you-change-the-key-of-an-array-element) – Jaquarh Jan 14 '22 at 11:47
  • Hi @Jaquarh and @CBroe, thanks for the attention, yes I haven't added the `unset` code in my PHP code, it did work when removing the `Info`, but it will be added as new and put in the last position, I used `array_replace` assuming it would take the `Info` array position. But still don't work, this really make me stuck – Maharlikan Jan 15 '22 at 04:42

0 Answers0