简体   繁体   中英

Need array in json with php json_encode

I have a array as this one :

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

After json_encode it gives me :

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

But i need :

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

How can i become that the Prices element is a array instead of a object ?

Currently the Prices element of your array is a single key-indexed array. To produce your desired result, it needs to be an array of key-indexed arrays.

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

DEMO

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

This will produce

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

You simply need to wrap your Prices data in another array.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM