user3248186
user3248186

Reputation: 1558

Converting sequential array to json after deleting some elements

So I've a json string and an array like so :

$json_str = '{"key1":["val11", "val12", "val13"], "key2":"val2"}';
$delete_keys = array("val12");

I want to delete the values present in delete_keys from json_str['key1']. So I did the following:

$json_arr = json_decode($json_str, true);
$key1 = $json_arr['key1'];
foreach ($delete_keys as $key) {
    $index = array_search($key, $key1);
    if (isset($index))
        unset($key1[$index]);
    unset($index);
}
$json_arr['key1'] = $key1;
$json_str = json_encode($json_arr);
print $json_str;

Now the result I expected for json_str is this

{"key1":["val11", "val13"], "key2":"val2"}

But instead I get this

{"key1":{"0":"val11", "2":"val13"}, "key2":"val2"}

It works as I expected if I delete the last key though. Can someone please tell me how to get the former as the json string instead of the latter.

Upvotes: 0

Views: 67

Answers (2)

Nikita
Nikita

Reputation: 408

You should reindex array with array_values().

If keys in the array are not sequential it is an associative array.

Upvotes: 1

sunil
sunil

Reputation: 601

There is an example of this phenomenon on the PHP documentation for json_encode, labelled with "Sequential array with one key unset": http://php.net/manual/en/function.json-encode.php

Reproduced here:

$sequential = array("foo", "bar", "baz", "blong");
// ...
unset($sequential[1]);
var_dump(
 $sequential,
 json_encode($sequential)
);
// Outputs: string(33) "{"0":"foo","2":"baz","3":"blong"}"

In order for the keys to remain sequential, you can re-number them using array_values:

$sequential = array("foo", "bar", "baz", "blong");
// ...
unset($sequential[1]);
$sequential = array_values( $sequential );
var_dump(
 $sequential,
 json_encode($sequential)
);
// Outputs: string(21) "["foo","baz","blong"]"

Upvotes: 0

Related Questions