Manolo
Manolo

Reputation: 26370

php json_encode single item numeric array

When I do json_encode from this array:

array('aps' => array(
                     'alert' => array(
                                     'param1'=>array('string'), 
                                     'param2'=>'string' )));

I'm getting this JSON object:

{
    "aps" :    {
      "alert" :         {
            "param1" :             {
                "0" : "string"
            },
            "param2" : "string"
        }
    }
}

Instead of

{
    "aps" :    {
      "alert" :         {
            "param1" :             
                ["string"],

            "param2" : "string"
        }
    }
}

It seems to work right when the param1 array is not a single item. How could I fix it? The Json is created from a third party bundle, so I should format the array in PHP so that I could get the correct JSON on json_encode (param1 as a list).

Upvotes: 1

Views: 3300

Answers (1)

DarkSide
DarkSide

Reputation: 3709

See this answer: https://stackoverflow.com/a/11722121/1466341

And more info here: http://www.php.net/manual/en/function.json-encode.php

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.

In your case everything should work fine, but I guess you have simplified your PHP array in this example. So, idea is simple - if your PHP array don't have all keys sequential, then json_encode will treat them as keys of object.

Upvotes: 2

Related Questions