【发布时间】:2016-06-11 05:03:12
【问题描述】:
我在 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 在第二个中没有用括号分隔。
【问题讨论】:
标签: php arrays json multidimensional-array