1

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.

asked Jun 4, 2015 at 13:33

2 Answers 2

1

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

answered Jun 4, 2015 at 13:40
Sign up to request clarification or add additional context in comments.

Comments

0

You can't have associative arrays in JSON. An associative array will always become an object in JSON after json_encode.

answered Jun 4, 2015 at 15:13

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.