【问题标题】:Make Array of Objects from json_encode从 json_encode 创建对象数组
【发布时间】:2015-06-04 13:33:04
【问题描述】:

我有这个对象

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 对象时做错了什么。

【问题讨论】:

    标签: php arrays json object


    【解决方案1】:

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

    这是一个例子

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

    生产

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

    这是live runnable demo

    【讨论】:

      【解决方案2】:

      JSON 中不能有关联数组。关联数组在 json_encode 之后总是会变成 JSON 中的对象。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-05-21
        • 1970-01-01
        • 2021-12-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多