我在使用PHP創建JSON時遇到問題;我從sql查詢中創建了一個while
循環中的數組。 $featuresCSV
是逗號分隔的字符串,如"1,3,4"
。在JSON中,我需要它最終像feature-1: 1,feature-2: 1,feature-3: 1
1
代表true
爲我的前端程序中的複選框。php json多維數組語法
while ($stmt2->fetch()) {
$features = array();
$featuresTmp = explode(',', $featuresCSV, -1);
foreach ($featuresTmp as &$featureItem) {
$features[] = array("feature-" . $featureItem => 1);
}
$items[] = array('price' => $price, 'image' => $image, 'features' => $features);
}
...
json_encode($output);
的JSON最終看起來像這樣:
{"price":8900,
"image":"4d3f22fe-9f1a-4a7e-a564-993c821b2279.jpg",
"features":[{"feature-1":1},{"feature-2":1}]}
,但我需要它看起來像這樣:
{"price":8900,
"image":"4d3f22fe-9f1a-4a7e-a564-993c821b2279.jpg",
"features":[{"feature-1":1,"feature-2":1}]}
注意如何feature-1
和feature-2
尚未通過支架分離第二。