我正在尝试使用四分之一小时填充下拉列表。键是选项值,值是选项文本。
private function quarterHourTimes() {
$formatter = function ($time) {
return date('g:ia', $time);
};
$quarterHourSteps = range(25200, 68400, 900);
return array_map($formatter, $quarterHourSteps);
}
问题是上面的函数有效,但似乎不能作为关联数组。这个问题有优雅的解决方案吗?
对于密钥,我希望时间格式为date('H:i', $time);
e.g。数组应如下所示:
$times =
[
['07:00' => '7:00am'],
['07:15' => '7:15am'],
['07:30' => '7:30am'],
['07:45' => '7:45am'],
['08:00' => '8:00am'],
['08:15' => '8:15am'],
...
];
我的解决方案 - 转储array_map:
private function myQuarterHourTimes()
{
$quarterHourSteps = range(25200, 68400, 900);
$times = array();
foreach(range($quarterHourSteps as $time)
{
$times[date('H:i', $time)] = date('g:ia', $time);
}
return $times;
}
答案 0 :(得分:1)
您的功能可以轻松替换为:
$result = array_reduce(range(25200, 68400, 900), function(&$cur, $x)
{
$cur[date('H:i', $x)] = date('g:ia', $x);
return $cur;
}, []);
结果为关联数组,如this。
答案 1 :(得分:0)
我想你正在寻找类似的东西
<?php
function formatter($time) {
return array (date('g:i', $time) => date('g:ia', $time));
};
function quarterHourTimes() {
$quarterHourSteps = range(25200, 68400, 900);
return array_map('formatter', $quarterHourSteps);
}
print_r (quarterHourTimes());
?>