-1

How can I re-index a JSON after using unset($json -> nodes[$data_deleteNode]) to remove an entry? The common method array_values($json), which usally close the gaps doesn´t work. I understand the error message but do not have an idea to solve it.

array_values() expects parameter 1 to be array, object given

There is a similar thread which refers to the solutions I tried - PHP json_encode as object after PHP array unset() the only difference is the JSON.

If I do not perform any sorting, unset() adds an index which cause my JSON to be not readable for other scripts.

enter image description here

The affected PHP:

<?php
header("Access-Control-Allow-Origin: *");

$data_deleteNode = ($_POST['id']); 

$json = file_get_contents("data2.json");
$json = json_decode($json);

//$data_deleteNode = json_decode($data_deleteNode);

//array_splice($json, 3, 1);

printf("%s\n", json_encode($json));

unset($json -> nodes[$data_deleteNode]);

printf("%s\n", json_encode($json));

$json = array_values($json);
$json = json_encode($json);

file_put_contents("data2.json", $json)

?>

UPDATE: modified playground which shows the error https://3v4l.org/XPbuo#v730

ICoded
  • 319
  • 3
  • 18
  • `$json` is an object. The array which you modify is `$json->nodes`. You want to run `array_values` on *that*. `$json->nodes = array_values($json->nodes)`. – deceze Jun 07 '21 at 10:03
  • What have you tried so far? Where are you stuck? Can you share sample input for your script, such that others could run it to help you? – Nico Haase Jun 07 '21 at 10:17
  • @deceze the error is gone but also the $json -> links values. The data2.json file only stores the nodes now. Thanks for your help so far. We may get into the solution. – ICoded Jun 07 '21 at 10:21
  • Sounds like you didn't assign the values back to ***`$json->nodes`***, but just directly wrote the return value of `array_values($json->nodes)` to the file… – deceze Jun 07 '21 at 10:22

1 Answers1

1
$json = file_get_contents("data2.json");
$data = json_decode($json);

unset($data->nodes[$data_deleteNode]);

$data->nodes = array_values($data->nodes);
    
$json = json_encode($data);
file_put_contents("data2.json", $json)

$data->nodes is the array you're modifying and that you need to reset. You do that with:

$data->nodes = array_values($data->nodes);

Note also that I renamed your variables so $json refers to JSON encoded text, and $data refers to decoded arrays/objects.

deceze
  • 510,633
  • 85
  • 743
  • 889