从数组中取消设置对象,然后解码 returns 不正确的格式 php

Unset an object from an array and then decode returns incorrect format php

我有一个 "components" 的数组以 json 格式存储在数据库中,我想删除(取消设置)一个项目,然后将其保存回数据库。

我遇到的问题是,当我取消设置该项目时,当我使用 json_encode() 并且格式不同时,它会为数组的位置添加额外的数字。所以我无法正确阅读它。

下面是它的存储方式 correctl:y Json string 然后 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
        )

)

下面是我取消设置 id 为 2 的项目后的 json_encoded 结果。它两边都没有方括号,在末尾添加了一个大括号并添加了数组位置。

{"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"}}


下面的代码是我对数据进行排序和删除项目的代码:

<?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;

结果如下" echo $newJson数据:

{"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"}}

您看到的行为是因为您不能将一个数组的键以 0 开头的不连续键表示为 JSON 中的数组,因此该数组必须采用对象形式(例如,当您删除你得到 {"0":{...}, "2":{...}} 的中间元素。要解决这个问题并获得你想要的结果,请使用 array_values 从 0:

开始重新索引 $dataToSort
$newJsonData = json_encode(array_values($dataToSort));

输出:

[
    {
        "id": "1",
        "component": "crank",
        "brand": "part1",
        "date_": "13\/11\/2019"
    },
    {
        "id": "3",
        "component": "bar",
        "brand": "part 3",
        "date_": "13\/11\/2019"
    }
]

Demo on 3v4l.org