dongyanhu5628 2016-02-28 02:00
浏览 47
已采纳

php json多维数组语法

I have a problem with the JSON I'm creating in PHP; I create the array in a while loop from an sql query. $featuresCSV is a comma-separated string like "1,3,4". In the JSON I need it to end up like feature-1: 1,feature-2: 1,feature-3: 1 The 1 represents true for my checkbox in my front-end program.

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);

The JSON ends up looking like this:

{"price":8900,
"image":"4d3f22fe-9f1a-4a7e-a564-993c821b2279.jpg",
"features":[{"feature-1":1},{"feature-2":1}]}

but I need it to look like this:

{"price":8900,
"image":"4d3f22fe-9f1a-4a7e-a564-993c821b2279.jpg",
"features":[{"feature-1":1,"feature-2":1}]}

Notice how feature-1 and feature-2 aren't separated by brackets in the second.

  • 写回答

2条回答 默认 最新

  • dougongyou7364 2016-02-28 02:04
    关注

    You need to assign the elements at "feature-1" and "feature-2".

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

    The syntax $feature[] = ... is for appending to the end of an array.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 手机应用的时间可以修改吗
  • ¥15 docker 运行OPEN-webui异常
  • ¥15 麒麟系统如何删除光盘刻录痕迹
  • ¥15 recipe通过gem协议传的是什么
  • ¥15 TS2307: Cannot find module 'cc'.
  • ¥15 100小时学会sap 书上pp章节5.22,标准成本计算逻辑?
  • ¥50 达梦数据库误删日志文件重做DAMENG01.log启动仍然-712错误
  • ¥15 cellranger化学处理类型报错
  • ¥15 用texstudio插入图片出现下面情况,怎么办
  • ¥15 ubantu 用samba挂载windows的共享文件夹,无法挂载二级目录和修改文件