【问题标题】:Need to merge many rows in one JSON需要在一个 JSON 中合并多行
【发布时间】:2015-04-20 00:48:00
【问题描述】:

如何制作:

 {"color":[{"id":"41","name":"red"}]}
 {"color":[{"id":"19","name":"blue"}]}
 ...

php 和 json_encode 这个东西

 {"color":[{"id":"41","name":"red"},{"id":"19","name":"blue"},...]}

数据来自数据库,我使用以下代码:

 $json = array();
 $jsonRow= array();
 while ($row = mysqli_fetch_array($getResult)) {
    $jsonRow = array(
        $row['color'] => array(
            array(
                "id" => $row['id'],
                "name" => $row['name'],
            )
        )
    );
    array_push($json,$jsonRow);
 }

【问题讨论】:

    标签: php mysql arrays json merge


    【解决方案1】:

    试试这个:

     $json = array();
     $jsonRow= array();
     while ($row = mysqli_fetch_array($getResult)) {
        $jsonRow[] = array(
           "id" => $row['id'],
           "name" => $row['name'],
        );
     }
     // color can be $row['color']
     // If its constant, I am not sure if its a good idea to keep in the loop.
     $json = array("color" => $jsonRow); 
     echo json_encode($json);
    

    【讨论】:

    • 错误。这会将数组转换为字符串。你不要用 json 那样做。 json 可以很好地处理嵌套数组/对象。
    • 你是对的,这个答案是根据 OP {"color":[{"id":"41","name":"red"},{"id":"19","name":"blue"},...]} 要求的输出。我怀疑 OP 建议的 json_encode() 可以带来这样的输出,所以......
    【解决方案2】:

    这个怎么样?

    $json = array();
    $colors= array();
    
     while ($row = mysqli_fetch_array($getResult)) {
    
            array_push($colors,
                array(
                    "id" => $row['id'],
                    "name" => $row['name'],
                )
        );
        $json = array( "colors" => $colors);
    
    }
    

    【讨论】:

      【解决方案3】:
       $arr= array();
       $jsonRow= array();
       while ($row = mysqli_fetch_array($getResult)) {
          $jsonRow =  array(
                      "id" => $row['id'],
                      "name" => $row['name'],
                  );
          $arr[]=$jsonRow;
       }
      $json = json_encode(array('color'=>$arr));
      echo $json;
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-05-19
        • 1970-01-01
        • 2012-01-22
        • 1970-01-01
        • 1970-01-01
        • 2011-08-02
        • 1970-01-01
        相关资源
        最近更新 更多