PHP JSON Encode not working

Blease picture Blease · Aug 2, 2013 · Viewed 7.7k times · Source

This is the var_dump of the array I want to encode into JSON:

array(3) { 
    [0]=> array(2) { 
        ["From"]=> string(14) "08 August 2013"
        ["To"]=> string(14) "21 August 2013"
    }
    [1]=> array(2) {
        ["From"]=> string(14) "11 August 2013"
        ["To"]=> string(14) "21 August 2013"
    }
    [2]=> array(2) { 
        ["From"]=> string(14) "12 August 2013" 
        ["To"]=> string(14) "01 August 2013" 
    } 
}

When I encode it, the output looks like this:

[
 {"From":"08 August 2013","To":"21 August 2013"},
 {"From":"11 August 2013","To":"21 August 2013"},
 {"From":"12 August 2013","To":"01 August 2013"}
]

But I want it to be this:

{
 0:{"From":"08 August 2013","To":"21 August 2013"}, 
 1:{"From":"11 August 2013","To":"21 August 2013"}, 
 2:{"From":"12 August 2013","To":"01 August 2013"}
}

It's possible because I've done it before, but using the same code now it won't work

Answer

JohnnyFaldo picture JohnnyFaldo · Aug 2, 2013

Use the : JSON_FORCE_OBJECT argument;

$json = json_encode($array,JSON_FORCE_OBJECT);

That will assign numeric keys