1

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.

6
  • Are you looking to add a new record (insert a new user) or to replace an existing user? If you're looking to replace an existing under, what field should this be based on? The email? The username? Commented May 31, 2021 at 7:22
  • I want to match the 'name'. if it match it will be replaced with the new data from POST. Commented May 31, 2021 at 7:24
  • Why try to achieve this using array splicing - you already have identified the element you want to replace, so just overwrite it? $data[$i] = $dataMerge; and done …? Commented May 31, 2021 at 7:26
  • Are you 100% sure that name is a unique identifier? Commented May 31, 2021 at 7:38
  • The second parameter to json_decode should be either true or false. Commented May 31, 2021 at 7:40

1 Answer 1

-1

Based on your answer to my comment, there are few things to change:

  1. The array_splice might not be the best solution here as you need to loop the array twice, while you can just do it once
  2. The $dataMerge variable should just be an object, not an array with a single object.

See below the revised code

$data = file_get_contents('users.json');
$data = json_decode($data, JSON_PRETTY_PRINT);
$dataMerge = [
    "name" => $_POST['name'],
    "username" => $_POST['username'],
    "email" => $_POST['email'],
    "phone" => $_POST['phone'],
    "website" => $_POST['website'],
];
foreach ($data as $key => $user) {
    if ($user['name'] == $dataMerge['name']) {
        $data[$key] = $dataMerge;
    }
}
$data = json_encode($data, JSON_PRETTY_PRINT);
file_put_contents('users.json', $data);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.