Stack Overflow is a community of 4.7 million programmers, just like you, helping each other.

Join them; it only takes a minute:

Sign up
Join the Stack Overflow community to:
  1. Ask programming questions
  2. Answer and help your peers
  3. Get recognized for your expertise

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.

share|improve this question

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

share|improve this answer

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

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.