2

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

Android Developer
  • 987
  • 1
  • 8
  • 22
Blease
  • 1,380
  • 4
  • 38
  • 64

4 Answers4

6

Many Times it occurs when our content of the array is not Encoded. Generally we use UTF-8 Encoding.

So, To Solve this issue Just add

mysqli_set_charset($con, 'utf8');

Just after the connection.

Dharmesh Patel
  • 131
  • 1
  • 5
4

Use the : JSON_FORCE_OBJECT argument;

$json = json_encode($array,JSON_FORCE_OBJECT);

That will assign numeric keys

JohnnyFaldo
  • 4,121
  • 4
  • 19
  • 29
  • also casting the array to object (`json_encode((object)$array);`) works too. underlying arrays wont be forced to object this way. this might be preferable in some cases – x4rf41 Aug 02 '13 at 14:25
1

Both versions are equivalent. JS by default will number the array elements starting with 0, so even though they're not specified, you'll still get 0,1,2,.... as the indexes when you decode later on.

You can trivially verify this by decoding the string, e.g.

$array = array('your array here');
$json = json_encode($array);
$decoded_array = json_decode($json);
var_dump($decoded_array);
Marc B
  • 356,200
  • 43
  • 426
  • 500
0

if you want those index because you want an array of json objects, you don´t need them because you already have that[] ,if you want to select any of those objects inside of the array you could already use index[] like:

example[0].from;

Every {} means an json object and [{},{},{}] means an array of objects.

Jao Assy
  • 115
  • 2
  • 6