I am using json_encode
to convert PHP arrays to json and it seems to work fine except for one thing.
If I have a multi-dimensional array like this:
$person = array(
'name' => 'John Smith',
'age' => 36,
'siblings' => array(
'male' => array('John Doe','Mark'),
'female' => array('Jane Doe','Jane Smith')
)
);
I want it to put brackets around siblings
but it only does it around male
and female
, i.e:
{
"name":"John Smith",
"age":36,
"siblings":{
"male":[
"John Doe",
"Mark"
],
"female":[
"Jane Doe",
"Jane Smith"
]
}
}
And I want "siblings":[{ ... }]
Is this possible?
$person = array(
'name' => 'John Smith',
'age' => 36,
'siblings' => array(array(
'male' => array('John Doe','Mark'),
'female' => array('Jane Doe','Jane Smith')
))
);
This will give exactly what you want but it doesn't make much sense
JavaScript does not support assosicative arrays, therefore assosicative arrays are converted to objects.
But you can iterate over objects like you can iterate over arrays.
var i, j;
for (i in siblings) {
for (j = 0; j < i.length; i++) {
i[j];
}
}
You could do something like this:
$person = array(
'name' => 'John Smith',
'age' => 36,
'siblings' => array(
array(
'gender' => 'male',
'name' => 'John Doe',
),
array(
'gender' => 'male',
'name' => 'Mark',
),
array(
'gender' => 'female',
'name' => 'Jane Doe',
),
array(
'gender' => 'female',
'name' => 'Jane Smith',
),
)
);