我以非常难以使用的格式从API中获取数据(在需要使用的mannor中) - 我无法修改API。以下是我给出的数据示例:
$data = array(
array('day' => 'Monday', 'start' => 1100, 'end' => 1300),
array('day' => 'Tuesday', 'start' => 1100, 'end' => 1300),
array('day' => 'Wednesday', 'start' => 1100, 'end' => 1300),
array('day' => 'Thursday', 'start' => 1200, 'end' => 1300),
array('day' => 'Friday', 'start' => 1200, 'end' => 1300),
array('day' => 'Saturday', 'start' => 1200, 'end' => 1300),
array('day' => 'Sunday', 'start' => 1200, 'end' => 1400)
);
数据可能不包括一周中的所有七天,开始和结束在0000和2400之间变化。我试图想出一种方法来使用以下输出格式化数据:Monday - Wednesday (1100-1300), Thursday - Saturday (1200-1300), Sunday (1200-1400)
基本上,连续天(其开始和结束时间相同)由一个超级分开。
我有点想避免一大堆难看的代码
答案 0 :(得分:2)
丑陋是旁观者的眼睛。 ;)我认为这是可以的,但当然它可能正是你想要避免的。
<?php
$data = array(
array('day' => 'Monday', 'start' => 1100, 'end' => 1300),
array('day' => 'Tuesday', 'start' => 1100, 'end' => 1300),
array('day' => 'Wednesday', 'start' => 1100, 'end' => 1300),
array('day' => 'Thursday', 'start' => 1200, 'end' => 1300),
array('day' => 'Friday', 'start' => 1200, 'end' => 1300),
array('day' => 'Saturday', 'start' => 1200, 'end' => 1300),
array('day' => 'Sunday', 'start' => 1200, 'end' => 1400)
);
$periods = array();
$start = $end = $i = -1;
foreach ($data as $datum) {
if ($start != $datum['start'] || $end != $datum['end']) {
$i++;
$start = $datum['start'];
$end = $datum['end'];
$periods[$i] = array(
'start' => $start,
'end' => $end,
'startDay' => $datum['day']);
}
$periods[$i]['endDay'] = $datum['day'];
}
foreach ($periods as $k => $period) {
echo ($k) ? ', ' : '';
if ($period['startDay'] === $period['endDay']) {
echo $period['startDay'];
} else {
echo "{$period['startDay']} - {$period['endDay']}";
}
echo " ({$period['start']} - {$period['end']})";
}
输出:
Monday - Wednesday (1100 - 1300), Thursday - Saturday (1200 - 1300), Sunday (1200 - 1400)
答案 1 :(得分:0)
我的解决方案:
function data_to_array(&$data, $cols) {
foreach($data as &$value) {
$value = array_combine($cols, explode(',', $value));
}
}
$data = Array(
'Monday,1200,1400',
'Monday,1200,1400',
'Monday,1200,1400',
'Monday,1200,1400',
'Monday,1200,1400',
'Monday,1200,1400',
'Monday,1200,1400',
'Monday,1200,1400',
'Monday,1200,1400',
'Monday,1200,1400',
'Monday,1200,1400'
);
data_to_array($data, Array('day','start','end'));
// now $data is again ugly block of data :)
现在您可以将其保存在文本文件中 的 data.txt中:强>
Monday,1200,1400
Monday,1200,1400
Monday,1200,1400
Monday,1200,1400
Monday,1200,1400
Monday,1200,1400
Monday,1200,1400
Monday,1200,1400
Monday,1200,1400
Monday,1200,1400
Monday,1200,1400
你的php文件:
$data = explode("\n", file_get_contents('data.txt'));
data_to_array($data, Array('day','start','end'));
// now $data is again ugly block of data :)