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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
  • donglan9651 2016-02-28 02:06
    关注

    Here ya go

    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);
    
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 Python词频统计,运行出的Excel没有内容
  • ¥15 求推荐一个好用的录屏软件
  • ¥15 kali显示no x11 display variable was set;
  • ¥15 如何实现这个Python开发问题
  • ¥15 Erasure Code纠删码表
  • ¥15 用vite创建的vue3项目,404重定向不起作用??
  • ¥15 关于#c语言#的问题:一个球从80米高度自由落下,每次落地后反弹的高度为原高度的一半计算6次小球反弹的高度.(反弹结果取整,使用走走for循环结构)
  • ¥15 SurfaceControl的screenshot问题
  • ¥15 基于51单片机的oled菜单代码,要C语言,模块化编程!
  • ¥15 JAVAswing,设计一个扑克牌什么的