从json_encode创建对象数组

时间:2015-06-04 13:33:05

标签: php arrays json 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
          )
        )
      )
    )
  )
) 

当我在其上制作json_encode时,我得到了这个json字符串

   {
      "reportDate":"2014-02-02",
      "shops":{
        "24":{
          "shopid":24,
          "cashiers":{
            "1":{
              "cashierid":1,
              "products":{
                "moneyIn":"46",
                "moneyOut":"215.14"
              }
            }
          }
        }
      }
    }

这个结果不是我想要的。我想要一些对象。

所以不是这个" shops":{我希望这个"shops":[ 而不是"cashiers":{我想要这个"cashiers":[等等。

我的stdClass中有一个数组,我想要数组,并且有stdClass,我想要对象。

那么在构造我的初始stdClass对象时我做错了什么。

2 个答案:

答案 0 :(得分:1)

如您所见,关联数组会生成一个对象。要生成JSON数组,您需要一个由数组组成的数组。

这是一个例子

$shops  = [['shopid'=>24, 'cashiers'=>[['cashierId'=>1]]]];

可生产

[
   {
      "shopid":24,
      "cashiers":[{"cashierId":1}]
   }
]

这是live runnable demo

答案 1 :(得分:0)

您不能在JSON中拥有关联数组。在json_encode之后,关联数组将始终成为JSON中的对象。

相关问题