如何在使用PHP删除ID后保留原始JSON格式

时间:2016-06-08 22:24:27

标签: php json string format

我有一个删除JSON字符串中的PID的函数。这个函数工作正常,但是当我用JSON格式再次编码结果字符串(使用json_encode)时,原始的JSON格式就会丢失。

如何保留此原始格式。这就是问题所在。我需要帮助才能做到。

这是代码:

function deletePID($idToRemove, $dataBase) {
    if (!empty($dataBase)) {
        $dataArray = json_decode($dataBase, true);
        if (is_array($dataArray)) {
            if (is_numeric($idToRemove)) {
                for ($i = 0; $i < count($dataArray['cP']); $i++) {
                    $thisChannel = $dataArray['cP'][$i]['cID'];
                    if ($idToRemove == $thisChannel) {
                        unset($dataArray['cP'][$i]);
                    }
                }
                $thisJason = json_encode($dataArray);
                return $thisJason;
            }
        }
    }
}

$database = '{"cP":[{"cID":"1","PID":"30144"},{"cID":"2","PID":"30147"},{"cID":"3","PID":"30150"}]}';

$pidToDelete = 2;

echo deletePID($pidToDelete, $database);

输出是:

{"cP":{"0":{"cID":"1","PID":"30144"},"2":{"cID":"3","PID":"30150"}}}

而不是:

{"cP":[{"cID":"1","PID":"30144"},{"cID":"3","PID":"30150"}]}

1 个答案:

答案 0 :(得分:1)

您需要连续索引才能以这种方式进行编码。使用array_values()重新编制索引:

$thisJason = json_encode(array_values($dataArray));