我的mysql数据库中有下表,其中包含开始和结束TIME数据类型的事件:
start_time end_time day
08:00:00 16:00:00 1
08:00:00 16:00:00 1
08:00:00 16:00:00 4
08:00:00 16:00:00 5
我想创建一个多维数组,每天都有一个数组中的start_time和end_time,就像这样;
array:3 [
1 => array:2 [
0 => array:2 [
0 => "08:00"
1 => "16:00"
]
1 => array:2 [
0 => "08:00"
1 => "16:00"
]
]
4 => array:1 [
0 => array:2 [
0 => "08:00"
1 => "16:00"
]
]
5 => array:1 [
0 => array:2 [
0 => "08:00"
1 => "16:00"
]
]
]
我有一个变量,其中包含我可以预先通过的所有事件。
这是可行的还是我需要使用数据透视表来保持这两个值分开?
谢谢!
答案 0 :(得分:1)
循环获取所提取的行并使用day
作为键并动态添加元素[]
并将时间指定为数组:
foreach($rows as $row) {
$result[$row['day']][] = array($row['start_time'],
$row['end_time']);
}
或者从DB获取时执行此操作:
while($row = /* fetch_function() */) {
$result[$row['day']][] = array($row['start_time'],
$row['end_time']);
}
答案 1 :(得分:1)
<?php
$records = array(
array(
'start_time' => '00:11:22',
'end_time' => '11:22:33',
'day' => 1
),
array(
'start_time' => '20:11:22',
'end_time' => '21:22:33',
'day' => 2
),
array(
'start_time' => '10:11:22',
'end_time' => '11:22:33',
'day' => 1
)
); // Your actual data would replace this of course
$sorted = array();
foreach($records as $record){
// Group by day
$sorted[$record['day']][] = $record;
}
// Group again
$results = array();
foreach($sorted as $day => $records){
foreach($records as $record){
$results[$day][] =
array($record['start_time'],$record['end_time']);
}
}
var_dump($results);