在PHP的集合中添加参数

时间:2018-10-19 12:42:35

标签: php object collections

嗨, 我有这个问题,用php返回这个集合

[{name: "DayOffice", pax: 3, id: 2, location: "Eur", type: "DAYOFFICE"},
{name: "HotDesking", pax: 3, id: 3, location: "Eur", type: "HOTDESKING"}]

我想要这样的东西:

[{name: "DayOffice", pax: 3, id: 2, location: "Eur", type: "DAYOFFICE","price":xxxx},
{name: "HotDesking", pax: 3, id: 3, location: "Eur", type: "HOTDESKING","price":xxxx}]

谢谢

1 个答案:

答案 0 :(得分:0)

首先,您的集合/字符串无效/不正确。要获得想要的内容,您必须通过用引号""括起键,然后将其解码为数组并将期望的键(例如,值pricexxxx)推入数组,以使其有效。

$obj = '[{"name":"DayOffice","pax":3,"id":2,"location":"Eur","type":"DAYOFFICE"},{"name":"HotDesking","pax":3,"id":3,"location":"Eur","type":"HOTDESKING"}]';

$array = json_decode($obj,1);
foreach($array as $key=> $row){
    $array[$key]['price'] = 'xxxx';
}

echo json_encode($array);

演示: https://3v4l.org/XaNMf