2016-02-28 81 views
2

我在使用PHP創建JSON時遇到問題;我從sql查詢中創建了一個while循環中的數組。 $featuresCSV是逗號分隔的字符串,如"1,3,4"。在JSON中,我需要它最終像feature-1: 1,feature-2: 1,feature-3: 11代表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-1feature-2尚未通過支架分離第二。

回答

2

您需要分配「特徵-1」和「特徵-2」的元素。

foreach ($featuresTmp as &$featureItem) { 
    $features["feature-" . $featureItem] = 1; 
} 

語法$feature[] = ...是用於附加到陣列的端部。

0

這裏亞去

while ($stmt2->fetch()) { 

$features = array(); 
$featuresTmp = explode(',', $featuresCSV, -1); 


foreach ($featuresTmp as &$featureItem) { 
$features["feature-$featureItem"] = 1; 
} 

$items[] = array('price' => $price, 'image' => $image, 'features' => $features); 
} 
... 
json_encode($output);