查询MySQL结果为多维关联PHP数组
Querying MySQL results into multi-dimensional associative PHP array
我可能忽略了一种相当简单的方法;也许有人知道如何通过有限的循环并且没有过长的查询来简化这件事。假设我有一个 MySQL table 数据如下:(有 12 个月,可能有 10 个不同的可能等级)。我将只查询给定 user_id 和年份的结果。
+----+---------+------+-------+-------+-------+
| id | user_id | year | month | grade | value |
+----+---------+------+-------+-------+-------+
| 1 | 1 | 2021 | Jan | A | 95 |
+----+---------+------+-------+-------+-------+
| 2 | 2 | 2021 | Jan | D | 75 |
+----+---------+------+-------+-------+-------+
| 3 | 2 | 2021 | Feb | F | 45 |
+----+---------+------+-------+-------+-------+
我希望能够查询数据并将其放入多维关联PHP数组中。
本质上,我可以这样访问数据:
echo $month_value['Jan']['D']; // Should give me 75
echo $month_value['Feb']['F']; // Should give me 45
找到一个适合我的简单方法:
$sql_retrieve = $con->prepare("SELECT month, grade, value
FROM table
WHERE user_id = ? AND year = ?;");
$bind_process = $sql_retrieve->bind_param('ii',$user_id,$year);
$sql_retrieve->execute();
$result = $sql_retrieve->get_result();
$month_values = []; // initialize array
if($result->num_rows > 0 ){ // If there are results
while($row=$result->fetch_assoc()){
$month_values[$row["month"]][$row["grade"]] = $row["value"]; // add to array
} // end while
} // end of if num_rows > 0
print_r($month_values); // Example
echo 'Value: '.$month_values['Jan']['D'];
然后将 MySQL 结果提供到多维关联 PHP 数组中,因此可以这样引用它们。
我可能忽略了一种相当简单的方法;也许有人知道如何通过有限的循环并且没有过长的查询来简化这件事。假设我有一个 MySQL table 数据如下:(有 12 个月,可能有 10 个不同的可能等级)。我将只查询给定 user_id 和年份的结果。
+----+---------+------+-------+-------+-------+
| id | user_id | year | month | grade | value |
+----+---------+------+-------+-------+-------+
| 1 | 1 | 2021 | Jan | A | 95 |
+----+---------+------+-------+-------+-------+
| 2 | 2 | 2021 | Jan | D | 75 |
+----+---------+------+-------+-------+-------+
| 3 | 2 | 2021 | Feb | F | 45 |
+----+---------+------+-------+-------+-------+
我希望能够查询数据并将其放入多维关联PHP数组中。 本质上,我可以这样访问数据:
echo $month_value['Jan']['D']; // Should give me 75
echo $month_value['Feb']['F']; // Should give me 45
找到一个适合我的简单方法:
$sql_retrieve = $con->prepare("SELECT month, grade, value
FROM table
WHERE user_id = ? AND year = ?;");
$bind_process = $sql_retrieve->bind_param('ii',$user_id,$year);
$sql_retrieve->execute();
$result = $sql_retrieve->get_result();
$month_values = []; // initialize array
if($result->num_rows > 0 ){ // If there are results
while($row=$result->fetch_assoc()){
$month_values[$row["month"]][$row["grade"]] = $row["value"]; // add to array
} // end while
} // end of if num_rows > 0
print_r($month_values); // Example
echo 'Value: '.$month_values['Jan']['D'];
然后将 MySQL 结果提供到多维关联 PHP 数组中,因此可以这样引用它们。