【问题标题】:Querying MySQL results into multi-dimensional associative PHP array将 MySQL 结果查询到多维关联 PHP 数组中
【发布时间】:2021-05-29 18:59:06
【问题描述】:

我可能忽略了一种相当简单的方法;也许有人知道如何通过有限的循环和没有过长的查询来简化此操作。假设我有一个 MySQL 表,其中包含如下数据:(有 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

【问题讨论】:

  • 如果这个问题悬而未决,它可能对其他人有所帮助,因为关于 PHP 中与存储来自 MySQL 查询的数据有关的多维关联数组的问题很少。

标签: php mysql multidimensional-array associative-array


【解决方案1】:

想出了一个适合我的简单方法:

$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 数组中,因此它们可以被引用。

【讨论】:

    猜你喜欢
    • 2013-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多