我在PHP中创建的JSON有问题; 我从 sql 查询在while
循环中创建数组。 $featuresCSV
是一个逗号分隔的字符串,如 "1,3,4"
. 在 JSON 中,我需要它像feature-1: 1,feature-2: 1,feature-3: 1
一样结束 1
表示我的前端程序中复选框的true
。
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
在第二个中没有用括号分隔。
您需要
在"功能-1"和"功能-2"处分配元素。
foreach ($featuresTmp as &$featureItem) {
$features["feature-" . $featureItem] = 1;
}
语法$feature[] = ...
用于追加到数组的末尾。
你去吧
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);