I have an array of "components" stored in a database in json format, I want to delete (unset) an item and then save it back to the database.
The problem I have is when I unset the item it adds extra numbers for the location of the array when I use json_encode() and has a different format. So I can't read it correctly.
Below is how it is stored correctl:y Json string then Array
[{"id":"1","component":"crank","brand":"part1","date_":"13/11/2019"},{"id":"2","component":"rim","date_":"13/11/2019","location":"Front","servicetype":"part 2"},{"id":"3","component":"bar","brand":"part 3","date_":"13/11/2019"}]
Array
(
[0] => stdClass Object
(
[id] => 1
[component] => crank
[brand] => part1
[date_] => 13/11/2019
)
[1] => stdClass Object
(
[id] => 2
[component] => rim
[date_] => 13/11/2019
[location] => Front
[servicetype] => part 2
)
[2] => stdClass Object
(
[id] => 3
[component] => bar
[brand] => part 3
[date_] => 13/11/2019
)
)
Below is the json_encoded result after I unset the item with id 2. It doesn't have the square brackets either side, adds a curly bracket to the end and adds array locations.
{"1":{"id":"2","component":"rim","date_":"13/11/2019","location":"Front","servicetype":"part 2"},"2":{"id":"3","component":"bar","brand":"part 3","date_":"13/11/2019"}}
The code below is what I have for sorting the data and removing the item:
<?php
$jsonData = '[{"id":"1","component":"crank","brand":"part1","date_":"13\/11\/2019"},{"id":"2","component":"rim","date_":"13\/11\/2019","location":"Front","servicetype":"part 2"},{"id":"3","component":"bar","brand":"part 3","date_":"13\/11\/2019"}]';
$id = 2;
$dataToSort = json_decode($jsonData);
foreach($dataToSort as $Key => $element) {
if ($element->id == $id) {
unset($dataToSort[$Key]);
echo $id . " Deleted\n";
}
}
$newJsonData = json_encode($dataToSort);
echo $newJsonData;
Result below" echo $newJsonData:
{"1":{"id":"2","component":"rim","date_":"13\/11\/2019","location":"Front","servicetype":"part 2"},"2":{"id":"3","component":"bar","brand":"part 3","date_":"13\/11\/2019"}}
The behaviour you are seeing is because you cannot represent an array with keys that are not consecutive starting with 0 as an array in JSON, so the array has to take an object form (e.g when you delete the middle element you get {"0":{...}, "2":{...}}
. To work around that and get the result you desire, use array_values
to re-index $dataToSort
starting at 0:
$newJsonData = json_encode(array_values($dataToSort));
Output:
[
{
"id": "1",
"component": "crank",
"brand": "part1",
"date_": "13\/11\/2019"
},
{
"id": "3",
"component": "bar",
"brand": "part 3",
"date_": "13\/11\/2019"
}
]