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;
}
2
  • 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. Commented Mar 4, 2014 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. Commented Mar 5, 2014 at 10:38

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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

1 Comment

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. codepad.org/rGffpsho

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.