我正在尝试建立一个项目管理系统,但在尝试对具有相同日期的项目进行分类时遇到了麻烦。例如,如果我今天发布了两个项目,昨天发布了两个项目,我希望它显示如下:
2019-06-01:
project 1
project 2
2019-05-31:
project 3
project 4
这是表格的样子
------------------------------------------------
id | project_name | date |
01 | project 1 | 2019-06-01 |
02 | project 2 | 2019-06-01 |
03 | project 3 | 2019-05-31 |
04 | project 4 | 2019-05-31 |
------------------------------------------------
这是我的代码:
<?php
include "connect.php";
$get_date = mysqli_query($con, "SELECT `date` FROM `projects` WHERE `user_id` = '1' GROUP BY `date`");
while($row = $get_date -> fetch_array()){
$date = $row['date'];
$string_date = strtotime($date);
echo $only_date = date('Y-m-d', $string_date) . "<br/>";
$get_project = mysqli_query($con, "SELECT * FROM `projects` WHERE `user_id` = '1' && `date` = '$date' GROUP BY `date` ORDER BY `date`");
while($d_row = $get_project -> fetch_array()){
$name = $d_row['project_name'];
echo $name . "<br/>";
}
}
?>
这是我的代码的输出:
2019-05-30
project 3
2019-05-30
project 4
2019-06-01
project 1
2019-06-01
project 2
答案 0 :(得分:1)
请考虑以下内容:
DLL:
DROP TABLE my_table;
CREATE TABLE my_table
(id SERIAL PRIMARY KEY
,project_name VARCHAR(12) NOT NULL
,date DATE NOT NULL
);
INSERT INTO my_table VALUES
(1,'project 1','2019-06-01'),
(2,'project 2','2019-06-01'),
(3,'project 3','2019-05-31'),
(4,'project 4','2019-05-31');
代码
<?php
include('path/to/connection/stateme.nts');
$query = "
SELECT date
, project_name
FROM my_table
ORDER
BY date DESC
, project_name; -- ORDER BY is not strictly necessary, as the ordering can be done in presentation code.
";
$result = mysqli_query($conn,$query);
$array = array();
while($row = mysqli_fetch_assoc($result)){
$array[] = $row;
}
$new_array = array();
foreach($array as $v){
$new_array[$v['date']][] = $v['project_name'];
}
print_r($new_array);
?>
输出:
Array
(
[2019-06-01] => Array
(
[0] => project 1
[1] => project 2
)
[2019-05-31] => Array
(
[0] => project 3
[1] => project 4
)
)
很显然,您可以坚持使用PDO方法