如何添加另一個具有資料值的物件?
事情開始像:
$data=[{name:"apple"}]
我想要這樣的輸出
$data=[{name:"apple",city:"gotham"}]
uj5u.com熱心網友回復:
不要嘗試手動構建 JSON,創建一個你想要的 PHP 資料結構,然后json_encode()用來將它變成一個 JSON 字串
$d = [(object)['name' => 'apple', 'city' => 'gotham']];
echo json_encode($d);
結果
[{"name":"apple","city":"gotham"}]
如果某些值已存在,則應將其解碼為 PHP 資料結構,然后添加到其中并轉換回 JSON 字串
$data='[{"name":"apple"}]';
$d = json_decode($data);
$d[0]->city = 'Gotham';
$data = json_encode($d);
結果
[{"name":"apple","city":"Gotham"}]
uj5u.com熱心網友回復:
您應該使用 json 物件格式: '[{"name":"value"}]' 然后使用 json_decode 將其從字串轉換為 json 物件。
$data = '[{"name":"apple"}]';
$data = json_decode($data);
$data[] = array('city' => 'gotham');
$data = json_encode($data);
echo $data;
輸出:
[{"name":"apple"},{"city":"gotham"}]
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/366613.html
