Reputation: 1406
I have this object
stdClass Object (
[reportDate] => 2014-02-02
[shops] => Array (
[24] => stdClass Object (
[shopid] => 24
[cashiers] => Array (
[1] => stdClass Object (
[cashierid] => 1
[products] => Array (
[moneyIn] => 46
[moneyOut] => 215.14
)
)
)
)
)
)
And When i make json_encode on it I get this json string
{
"reportDate":"2014-02-02",
"shops":{
"24":{
"shopid":24,
"cashiers":{
"1":{
"cashierid":1,
"products":{
"moneyIn":"46",
"moneyOut":"215.14"
}
}
}
}
}
}
This result is not what I wanted. I want array of objects.
So instead of this "shops":{
I want this "shops":[
Instead of this "cashiers":{
I want this "cashiers":[
And so on.
Where ever there is an array in my stdClass I want array and where there is stdClass I want object.
So what am I doing wrong in structuring my initial stdClass Object.
Upvotes: 1
Views: 207
Reputation: 3630
An associative array results in an object, as you've seen. To produce a JSON array you need an array composed of arrays.
Here's an example
$shops = [['shopid'=>24, 'cashiers'=>[['cashierId'=>1]]]];
Produces
[
{
"shopid":24,
"cashiers":[{"cashierId":1}]
}
]
And here's the live runnable demo
Upvotes: 1
Reputation: 631
You can't have associative arrays in JSON. An associative array will always become an object in JSON after json_encode.
Upvotes: 0