How to keep original Json format after deleting ID using PHP

Hi all,

I have a function to delete a PID inside a Json string. This function works fine, but when I encode in Json format the resulting string again (using json_encode), the original Json format is lost.

How to keep this original format. That’s the question. I need help to do it.

This is the code:

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

/*
Output is:

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

instead of ...

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

*/

Any help is really helpful and welcome.

Best,
Mapg

1 Like

main problem seems like your array is converted to an object with numeric properties, that will happen if your array keys have gaps, produced by your unset. get your data from array_values() on the resulting array to rearrange the keys, after that use json_encode().

Thank you chorn.

I did it as you mentioned and works.

Thanks again

Regards,
Mapg

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.