0

I am trying to populate a dropdown list with quarter hour times. The key being the option value, and the value being the option text.

private function quarterHourTimes() {
      $formatter = function ($time) {
          return date('g:ia', $time);
      };
      $quarterHourSteps = range(25200, 68400, 900);

      return array_map($formatter, $quarterHourSteps);
}

The problem is that the above function works, but does not seem to work as an associative array. Is there an elegant solution for this problem?

For the key, I wish to have the time in the following format date('H:i', $time);

e.g. array should look like this:

$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'],
    ...
];

My Solution - Dump the 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;
}
Gravy
  • 12,264
  • 26
  • 124
  • 193
  • 1
    Be careful with the word "recursive": `array_map()` applies the function you give it to each element in the array you provide. If the callback function you provide doesn't call itself, then there's no recursion. – crennie Mar 04 '14 at 18:30
  • 1
    @crennie - You are right, well spotted. - I tried to do it recursively before, and the question was related to doing it recursively. In attempt to solve the problem I removed the recursion, but forgot to change the title. My bad. – Gravy Mar 05 '14 at 10:38

2 Answers2

1

Your function can be easily replaced with:

$result = array_reduce(range(25200, 68400, 900), function(&$cur, $x)
{
   $cur[date('H:i', $x)] = date('g:ia', $x);
   return $cur;
}, []);

with result in associative array like this.

Alma Do
  • 37,009
  • 9
  • 76
  • 105
0

I suppose you are looking for something like this

<?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());

?>

Demo

code-jaff
  • 9,230
  • 4
  • 35
  • 56
  • Your function is great - but the array keys are wrong. Need the following output. I guess that I cannot use array_map for this purpose. http://codepad.org/rGffpsho – Gravy Mar 05 '14 at 10:35