Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/288.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
将MySQL结果查询成多维关联PHP数组_Php_Mysql_Multidimensional Array_Associative Array - Fatal编程技术网

将MySQL结果查询成多维关联PHP数组

将MySQL结果查询成多维关联PHP数组,php,mysql,multidimensional-array,associative-array,Php,Mysql,Multidimensional Array,Associative Array,我可能忽略了一个相当简单的方法;也许有人知道如何通过有限的循环和不需要过长的查询来简化这一过程。假设我有一个MySQL表,其中包含如下数据:(有12个月,可能有10个不同的等级)。我将查询出给定用户id和年份的结果 +----+---------+------+-------+-------+-------+ | id | user_id | year | month | grade | value | +----+---------+------+-------+-------+-------

我可能忽略了一个相当简单的方法;也许有人知道如何通过有限的循环和不需要过长的查询来简化这一过程。假设我有一个MySQL表,其中包含如下数据:(有12个月,可能有10个不同的等级)。我将查询出给定用户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数组,这样就可以引用它们。

如果这个问题没有解决,可能会对其他人有所帮助,因为PHP中的多维关联数组很少涉及存储MySQL查询中的数据。