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.

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

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.

Comments

Your Answer

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.