【发布时间】:2015-02-25 12:55:24
【问题描述】:
我正在尝试为图书馆预订系统创建一些统计数据。我的 sql 查询结果如下所示。
total_no_students|部门 |房产 |月 241 |物理学 |本科 |十一月 236 |物理学 |本科 |十二月 254 |物理学 |研究生 |十一月 210 |物理学 |研究生 |十二月 193 |建筑|本科 |十一月 181 |建筑|本科 |十二月 127 |建筑|研究生 |十一月 292 |建筑|研究生 |十二月 134 |生物学 |本科 |十一月 188 |生物学 |本科 |十二月 129 |生物学 |研究生 |十一月 219 |生物学 |研究生 |十二月我正在尝试使用 php 编写一些代码以创建具有以下外观的统计表:
|物理-本科|物理-研究生|建筑-本科|建筑-研究生| 十一月 | 241 | 254 | 193 | 127 | 十二月 | 236 | 210 | 181 | 292 |我必须使用数组和一些循环(foreach)通过 php(枢轴技术)对其进行转换。我尝试这样做,但我对嵌套循环感到困惑。
我写的代码如下:
$csvArray = 数组(); $departments = array('物理学','建筑','生物学'); $properties = array('本科','研究生'); $con = mysqli_connect($mysql_hostname, $mysql_user, $mysql_password, $mysql_dbname); $sql="SELECT count(id) as total_no_students, department, property, MONTH(table1.created) as month 从表 1 左 JOIN table2 ON table2.barcode=table1.input 按部门、财产、月份分组”; $res=mysqli_query($con,$sql); 而($row=mysqli_fetch_array($res)){ $time = $row['month']; if (!array_key_exists($time, $csvArray) ) { foreach ($departments 作为 $department) { $csvArray[$department] = array(); foreach($properties 作为 $property) { $csvArray[$department][$property] = array(); } } } $department = $row['department']; $property = $row['property']; $total_no_students = $row['total_no_students']; $csvArray[$time][$departments][$property] = $total_no_students; }任何帮助如何使用 php 将查询转换为上表?
【问题讨论】:
-
请标记您的问题与您正在使用的 SQL 实现(即 MySQL、SQL Server 等)
-
你能贴出你的php代码吗?但我会使用“月”作为数组的键
-
请显示您尝试的代码。我们会帮助您解决您尝试过的问题,我们不会为您解决。
-
我已经使用 SQL 实现了它(在 Saharsh Shah 的帮助下),但是当您有许多部门和属性时,SQL 查询变得非常庞大。所以我必须通过使用 php 数组的枢轴技术来做到这一点
标签: php mysql pivot aggregate-functions