【问题标题】:To build a multi-dimensional json array in PHP在 PHP 中构建多维 json 数组
【发布时间】:2014-02-01 06:28:57
【问题描述】:

我想要一个特定 json 格式的多维数组,该数组来自通过 sql 查询返回的表。该表如下所示:(请原谅原始格式)

|日期 |计数 |姓名 |

| 2013-12-19 | 252 |值 1 |

| 2013-12-19 | 60 |值 2 |

| 2013-12-19 | 8 |值 3 |

| 2013-12-26 | 173 |值 1 |

| 2013-12-26 | 32 |值 2 |

| 2013-12-26 | 6 |值 3 |

我想要一个下面提到的格式的多维 json 数组:

{2013-12-19: [{Name:"Value 1",Count:"252"},{Name:"Value 2",Count:"60"},{Name:"Value 3",Count :"8"}],

2013-12-26: [{Name:"Value 1",Count:"173"},{Name:"Value 2",Count:"32"},{Name:"Value 3",Count: "6"}] }

我尝试了一个代码,但在添加该数组中的所有日期值时遇到了麻烦。 这是我尝试过的示例代码:

    $query2_result = mysql_query($query2) or die(mysql_error());
    $rows_query2 = mysql_num_rows($query2_result);
    $records = array();

    if($rows_query2 > 0) {
     while($r = mysql_fetch_array($query2_result)) {
        if(!array_key_exists($r[date][name],$records[$r[date]])) {
                    $records[$r[date]][name] = array();

        }

         $records[$r[date]]["count"] = $r[count];
         $records[$r[date]]["name"] = $r[name];
      }
    }
    echo json_encode($records);

对于提到的每个日期,我只得到一个数组。像这样:

{"2013-12-19":{"name":"值 1","count":"775"},"2013-12-26":{"name":"值 1","计数":"397"}}

Kindle 帮帮我。非常感谢。

【问题讨论】:

  • 考虑使用 mysqli 而不是已弃用的 mysql。

标签: php mysql json multidimensional-array


【解决方案1】:
 $records = array();

 if($rows_query2 > 0) {
 while($r = mysql_fetch_array($query2_result)) {
      $records[$r['date']][] = array('name'=>$r['name'],'count'=>$r['count']);
 }

【讨论】:

    【解决方案2】:

    我认为将给定日期的所有记录添加到子数组所需要做的就是:

    $records[$r[date]][] = $r;
    

    【讨论】:

      【解决方案3】:

      用下面的逻辑改变while逻辑

      while($r = mysql_fetch_array($query2_result)) {
          $records[$r["date"]][]  = array(  "Name" => $r["name"], "Count" => $r["count"]);
      }
      

      【讨论】:

        猜你喜欢
        • 2012-12-14
        • 1970-01-01
        • 1970-01-01
        • 2019-10-14
        • 2023-03-21
        • 2016-09-28
        • 2017-04-04
        • 2013-10-27
        • 1970-01-01
        相关资源
        最近更新 更多