-5

所以这是我的代码:

Array ( [0] => 0 [1] => 1 [2] => 2 [3] => 3 [4] => 4 [5] => 5 [6] => 6 [7] => 7 [8] => 8 [23] => 23 [24] => 24 )

它缺少一些键,我想根据那些缺少的键将这个数组分成两部分,然后显示这两个数组中的最高和最低键......

例如:0-8 和 23-24

帮助!

4

3 回答 3

1

此代码可能会解决您的问题:

$arr = array("1" => "1", "2" => "2", "4" => "4", "5" => "5", "8" => "8", "9" => "9", "10" => "10", "11" => "11", "12" => "12", "16" => "16");
$arr_result = array();

$arr_keys = array_keys($arr);

$start = intval($arr_keys[0]);
$end = intval($arr_keys[count($arr_keys)-1]);

$group_idx = 0;

$idx = $start;
foreach($arr_keys as $x => $key) {
    if (intval($key) == intval($idx)) {
        $arr_result[$group_idx][$key] = $arr[$key];
        $idx++;
    } else {
        $group_idx++;
        $arr_result[$group_idx][$key] = $arr[$key];
        $idx = intval($key) + 1;
    }

}

print_r($arr_result);

我对其进行了测试,并且完全按照您的要求运行:)。结果是:

Array
(
    [0] => Array
        (
            [1] => 1
            [2] => 2
        )

    [1] => Array
        (
            [4] => 4
            [5] => 5
        )

    [2] => Array
        (
            [8] => 8
            [9] => 9
            [10] => 10
            [11] => 11
            [12] => 12
        )

    [3] => Array
        (
            [16] => 16
        )

)
于 2012-07-12T08:28:15.623 回答
0
$hours = range(0,24);
for($i = 5; $i <= 16; ++$i)
    unset ($hours[$i]);

foreach($hours as $key => $hour) {
    $hours[$key] = array($hour);
    if (isset($hours[$key-1])) {
        $hours[$key] = $hours[$key-1];
        $hours[$key][1] = $hour;
        unset($hours[$key-1]);
    }

}
$hours = array_values($hours);

var_dump($hours);
于 2012-07-12T10:33:05.840 回答
0
$test = array ("0" => 0, "1" => 1, "2" => 2, "3" => 3, "4" => 4, "5" => 5, "6" => 6, "7" => 7, "8" => 8, "23" => 23, "24" => 24, "25" => 25, "27" => 27, "28" => 28);

$full = range(reset($test),end($test));
$diff = (array_diff($full,$test));
$found = FALSE;
$start = reset($test);

for ($i = 0; $i < count($full); $i++)
    {
    if (array_key_exists($i, $diff))
        {
        if (!$found)
            {
            $str[] = $start."-".($i-1);
            $start = NULL;
            }

        $found = TRUE;
        }
    else
        {
        if (is_null($start))
            $start = $i;
        $found = FALSE;
        }
    }

$str[] = $start."-".($i-1);

print_r($str);

结果:

Array
(
    [0] => 0-8
    [1] => 23-25
    [2] => 27-28
)
于 2012-07-12T08:30:31.123 回答