0

I have an array that has all of the hours of the day listed, 0-23 like this:

[0] = 0  [1] = 1 [2] = 2 .... etc

Then I used date('G') to find the current hour, for example, 17.

What I want to do is reorder my array so that it starts with the next hour, 18, and then 19, 20, 21, 22, 23, 0, 1, 2.. etc

What is the best way to do this? I am feeding this array to a chart that is showing data over the time and having it in this order would really make things easier.

Jay
  • 443
  • 8
  • 23
  • You splice it at that hour, then move it to the front. – Kermit Jan 22 '13 at 22:50
  • What do you need the initial array for? Find the current hour, then generate the final array you need directly. `$result = array_merge(range($currentHour, 23), $currentHour ? range(0, $currentHour - 1) : array())` – Jon Jan 22 '13 at 22:53
  • You are trying to **rotate** an array. That's how it's called. See http://stackoverflow.com/questions/5601707/php-rotate-an-array –  Jan 22 '13 at 22:52

3 Answers3

2

This should work:

$array = array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23);

for($i = 0; $i < date("G"); $i++)
    array_push($array, array_shift($array));

print_r($array);

Assuming date("G") is 14, the result would be:

Array
(
    [0] => 14
    [1] => 15
    [2] => 16
    [3] => 17
    [4] => 18
    [5] => 19
    [6] => 20
    [7] => 21
    [8] => 22
    [9] => 23
    [10] => 0
    [11] => 1
    [12] => 2
    [13] => 3
    [14] => 4
    [15] => 5
    [16] => 6
    [17] => 7
    [18] => 8
    [19] => 9
    [20] => 10
    [21] => 11
    [22] => 12
    [23] => 13
)
Kermit
  • 33,827
  • 13
  • 85
  • 121
1
function rearrangeHours(&$hours, $hour_key){
  $beforeNow = array_slice($hours,0,$hour_key+1);
  $afterNow = array_slice($hours,$hour_key+1);
  return $hours = array_merge($afterNow, $beforeNow);
}

Then you can just do

$hours = range(0,23);
rearrangeHours($hours, 15);
Esben Tind
  • 885
  • 4
  • 14
1

I found a nice solution with InfiniteIterator and LimitIterator. You don't need to change the array. You can work directly with the iterator.

$array = range(0, 23);

$start = date("G") + 1;
$count = 24;

$infinate = new InfiniteIterator(new ArrayIterator($array));
$limit = new LimitIterator($infinate, $start, $count);

Then you can use $limit like an array.

foreach ($limit as $value) {
    print($value . PHP_EOL);
}
bitWorking
  • 12,485
  • 1
  • 32
  • 38