doucanshou6998 2016-07-20 18:18
浏览 19
已采纳

PHP:有一个现有的2D数组,并希望从mySQL查询中添加另一列

I would like to generate a 2-dimensional array that expands as I add the results from multiple SQL queries. I'm struggling with 2 different problems depending on how I approach the issue.

The initial query

$query = "SELECT YEAR(`Date`) as Year, count(*) as Total FROM `t_Table` GROUP BY YEAR(`Date`)";
if ($result = $mysqli -> query($query)) {
    while($row = $result -> fetch_array()) {
        <some action to get these results into a 2-D array>
    }
    $result->close();
}

Approach 1: use Year as the index

The following works to create the array but uses a numeric index:

$arr_result[] = array("Year" => $row["Year"], "Total" => $row["Total"]);

This produces:

Array (
    [0] => Array ( [Year] => 2015 [Total] => 158322 )
    [1] => Array ( [Year] => 2016 [Total] => 47908 )
)

What do I need to do to make Year the index? I've tried this but it doesn't work:

$arr_result[$row["Year"]] = "TotApts" => $row["TotApts"]);

and this:

$arr_result[$row[0]]["TotApts"] => $row["TotApts"];

What am I missing?

Approach 2: keep the index numeric and add additional columns to each row

So bring in query number 2 which extracts Year and count of Gender from the DB and I've verified that all is good as follows:

while($row = $result -> fetch_array()) {
    printf("Year %s - Gender %s<br>", $row["Year"], $row["Gender"]);
}

This produces

Year 2015 - Gender 91819
Year 2016 - Gender 27930

But I'm banging my head as to how to insert these into $arr_result so that I produce the following:

Array (
    [0] => Array ( [Year] => 2015 [Total] => 158322 [Gender] => 91819 )
    [1] => Array ( [Year] => 2016 [Total] => 47908 [Gender] => 27930 )
)

For example, I've tried among many many other (equally wrong) permutations:

$arr_result[][$row["Year"] = array("Gender" => $row["Gender"]);

Given use of the numeric index, do I need to loop through them (from i = 0 to x) from within the fetch_array() while loop and check that Year = the query year and only then update the value? Seems like that's a bit of unnecessary complexity. Am sure there is simpler approach...

  • 写回答

1条回答 默认 最新

  • duanqiu3800 2016-07-20 18:26
    关注

    Try the following in the first approach:

    $arr_result[$row["Year"]]["TotApts"] = $row["TotApts"];
    

    In the second approach you can do this:

    $arr_result[] = array( Year" => $row["Year"], "Total" => $row["TotApts"], "Gender" => $row["Gender"] )

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 BP神经网络控制倒立摆
  • ¥20 要这个数学建模编程的代码 并且能完整允许出来结果 完整的过程和数据的结果
  • ¥15 html5+css和javascript有人可以帮吗?图片要怎么插入代码里面啊
  • ¥30 Unity接入微信SDK 无法开启摄像头
  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算