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

    The problem is this -

    Note:

    When encoding an array, if the keys are not a continuous numeric sequence starting from 0, all keys are encoded as strings, and specified explicitly for each key-value pair.

    You need to re-sequence the array keys. Add the following line before the json_encode() line of code -

    $dataArray['cP'] = array_values($dataArray['cP']);

      Ohh!! Thank you very much. I worked great! I take note for future cases.

      Thanks again.

      Kind regards,
      Mapg

        Write a Reply...