0

I'm trying to edit json item property value by id, but it deleted all content exept the specific item i updated.

$projectsArr = json_decode(file_get_contents("../db/memory.json"), true);

foreach($projectsArr['memory'] as $mydata) {
    if($mydata['id'] == $_POST['id']) {
      $mydata['approved'] = true;
      $json = json_encode($mydata, JSON_UNESCAPED_UNICODE);
      file_put_contents('../db/memory.json', $json);
    }
}
eladr
  • 343
  • 1
  • 4
  • 18

1 Answers1

2

Only store the json back into the file after editing the data

<?php
    foreach($projectsArr['memory'] as &$mydata) {
        if($mydata['id'] == $_POST['id']) $mydata['approved'] = true;
    }

    $json = json_encode($projectsArr, JSON_UNESCAPED_UNICODE);
    file_put_contents('../db/memory.json', $json);
}

Also note that a foreach will create a temporary copy of the data, hence I use & to create a reference to the original data. More information about that here

DarkBee
  • 16,592
  • 6
  • 46
  • 58