【问题标题】:php json multidimensional array syntaxphp json多维数组语法
【发布时间】: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-1feature-2 在第二个中没有用括号分隔。

【问题讨论】:

    标签: php arrays json multidimensional-array


    【解决方案1】:

    您需要在“feature-1”和“feature-2”处分配元素。

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

    $feature[] = ... 语法用于追加到数组的末尾。

    【讨论】:

      【解决方案2】:

      来吧

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

      【讨论】:

        猜你喜欢
        • 2013-10-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-03-27
        • 2016-05-23
        • 2020-06-21
        • 2021-02-19
        • 1970-01-01
        相关资源
        最近更新 更多