首页 > 解决方案 > 需要在 json 中使用 php json_encode 的数组

问题描述

我有一个这样的数组:

$priceArray = [
            'pricing' => [
                'Prices' => [
                   'quantity' => 1,
                   'price' => floatval($price)
                ]
           ]
        ];

在 json_encode 之后它给了我:

{"pricing":
     {"Prices":
        {"quantity":1,
          "price":24
        }
    }
}

但是我需要 :

{
    "pricing":
       {"Prices":[
           {"quantity":1,
              "price":24
           }
      ]
   }
}

我怎样才能使价格元素是一个数组而不是一个对象?

标签: phpjson

解决方案


目前Prices,您的数组元素是单个键索引数组。为了产生您想要的结果,它需要是一个键索引数组的数组。

$priceArray = [
        'pricing' => [
            'Prices' => [
               [
                   'quantity' => 1,
                   'price' => floatval($price)
               ]
            ]
       ]
    ];

演示


推荐阅读