0

i have a problem with my json index remover , so far i tryed this

$cars = json_decode($json_user , true);
foreach ($cars as $key => $value) {
    if (in_array('BH', $value)) {
        unset($cars[$key]);
    }
}
echo $cars = json_encode($cars);

With the JSON content

[{"code":"AB"},{"code":"BC"},{"code":"CD"}]

When using the script above to remove the index containing BC it returns me this

{"0":{"code":"AB"},"2":{"code":"CD"}}

instead of this

[{"code":"AB"},{"code":"CD"}]
0

2 Answers 2

3

The JSON format is based in JavaScript syntax and JavaScript arrays cannot have sparse keys. Try dropping current keys and reindexing the array:

echo $cars = json_encode(array_values($cars));
Sign up to request clarification or add additional context in comments.

Comments

2

It works as expected. The PHP arrays are association maps. Removing a key doesn't affect the other keys of the array.

Use array_values() to reindex $cars before encoding it as JSON.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.