Kenneth P.
Kenneth P.

Reputation: 1816

weird behavior of json_encode function

I have this normal array name $arr.. and trying to push something on the array using array_push() function.. like array_push( $arr['alerts_data'], 999 ); It produces this output:

Array
(
    [alerts_data] => Array
        (
            [0] => 169
            [1] => 175
            [2] => 111
            [3] => 48
            [4] => 999
        )

)

When i use json_encode I got:

{"alerts_data":[169,175,111,48,111,999]}

BUT, when I try to unset() something from $arr like:

unset( $arr['alerts_data'][4] );// will remove removes the 999

and then use the json_encode again, I got this json object

{"alerts_data":{"0":169,"1":175,"2":111,"3":48}}

What's wrong in here? can you tell? I want to achieve the first encoded json above by using the unset() function.

Upvotes: 0

Views: 81

Answers (2)

Madara's Ghost
Madara's Ghost

Reputation: 175088

Yes, it's because the array keys aren't consecutive anymore, so it's treated as an associative array, and PHP associative arrays become JavaScript objects, because JavaScript does not have associative arrays.

Use array_splice() to cleanly remove elements from the array.

Upvotes: 4

Explosion Pills
Explosion Pills

Reputation: 191809

You have a gap in your keys (it goes from 3 to 5), so an object must be created for it to be valid. Two possible solutions:

array_splice($arr['alerts_data'], 4, 1);

unset($arr['alerts_data'][4]);
$arr['alerts_data'] = array_values($arr['alerts_data']);

Upvotes: 2

Related Questions