In my code I want to replace the whole object with new values if the name match.
$data = file_get_contents('users.json');
$data = json_decode($data, JSON_PRETTY_PRINT);
$dataMerge = array([
"name" => $_POST['name'],
"username" => $_POST['username'],
"email" => $_POST['email'],
"phone" => $_POST['phone'],
"website" => $_POST['website'],
]);
$nameToUpdate = $_POST['name'];
for ($i = 0; $i < count($data); $i++) {
$row = $data[$i];
if ($row['name'] == $nameToUpdate) {
$position = $i;
break;
};
}
$data = array_splice($dataMerge, $position);
// $json = json_encode($data);
$data = json_encode($data, JSON_PRETTY_PRINT);
file_put_contents('users.json', $data);
When you run this code it will delete all the objects on the json file and insert the new object. I just want to replace a certain object.
$data[$i] = $dataMerge;and done …?json_decodeshould be either true or false.