Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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;
}
share|improve this question
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 4 '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 5 '14 at 10:38

2 Answers 2

up vote 1 down vote accepted

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.

share|improve this answer

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

share|improve this answer
    
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 –  Gravy Mar 5 '14 at 10:35

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.