开发者

Create blocks of times from multidimensional array

I am working on a scheduling system and I need to grab all consecutive times of 4 or more开发者_运维技巧 which I have accomplished:

Array
(
    [0] => Array
        (
            [0] => 18:00:00
            [1] => 19:00:00
            [2] => 20:00:00
            [3] => 21:00:00
            [4] => 22:00:00
        )

    [1] => Array
        (
            [0] => 09:00:00
            [1] => 10:00:00
            [2] => 11:00:00
            [3] => 12:00:00
            [4] => 13:00:00
            [5] => 14:00:00
            [6] => 15:00:00
            [7] => 16:00:00
        )

)

How would I take this multidimensional array and put them into potential time blocks of four as check boxes?

For instance:

Checkbox 1 = 18:00:00 - 21:00:00

Checkbox 2 = 19:00:00 - 22:00:00

Checkbox 3 = 09:00:00 - 12:00:00

Checkbox 4 = 10:00:00 - 13:00:00

and so on...

Any help would be much appreciated as this has been racking my brain for hours.

Thanks in advance for any help.


Try this:

$a = array(
    array("18:00:00", "19:00:00", "20:00:00", "21:00:00", "22:00:00"),
    array("09:00:00", "10:00:00", "11:00:00", "12:00:00", "13:00:00", "14:00:00", "15:00:00", "16:00:00")
);
foreach ($a as $group)
{
    for ($i = 3; $i < count($group); ++$i)
    {
        print $group[$i-3] . " - " . $group[$i] . "<br />"; 
    }
}

Output:

18:00:00 - 21:00:00
19:00:00 - 22:00:00
09:00:00 - 12:00:00
10:00:00 - 13:00:00
11:00:00 - 14:00:00
12:00:00 - 15:00:00
13:00:00 - 16:00:00


Well, the way I see it is that you want to stack the sub-arrays into one large array and then split those up into four parts, from which you want to select the minimum and maximum value to display on your web page? The way I would do that, is as follows:

  1. Fetch all of the sub-array values and put them in one large array
  2. Sort the large array
  3. Split the large array into four segments
  4. Loop through the splitted array and fetch the minimum and maximum values
  5. Display those on your page.

This is what the code could look like:

// Setting: Amount of checkboxes
$div = 4;

$a = array(
    array("18:00:00", "19:00:00", "20:00:00", "21:00:00", "22:00:00"),
    array("09:00:00", "10:00:00", "11:00:00", "12:00:00", "13:00:00", "14:00:00", "15:00:00", "16:00:00")
);

$a_tot = array_unique(array_merge($a[0], $a[1]));
$count = count($a_tot);
$num_per = ceil($count / $div);

sort($a_tot);
$a_new = array();
$i = 0;
while (!empty($a_tot[$i])) {

    $a_new[] = array_slice($a_tot, $i, $num_per);
    $i += $num_per;

}

$chk_opt = array();
for ($i=0; $i<$div; $i++) {

    $chk_opt[] = sprintf("%s - %s", min($a_new[$i]), max($a_new[$i]));

}

unset ($a_tot, $count, $num_per, $a_new);

Output:

array(4) {
    [0]=> string(19) "09:00:00 - 12:00:00"
    [1]=> string(19) "13:00:00 - 16:00:00"
    [2]=> string(19) "18:00:00 - 21:00:00"
    [3]=> string(19) "22:00:00 - 22:00:00"
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜