PHP - 基于缺少的键拆分数组

时间:2012-07-12 07:44:16

标签: php arrays split

所以这是我的代码:

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

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

EX:0-8& 23-24

帮助!

3 个答案:

答案 0 :(得分: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
        )

)

答案 1 :(得分: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
)

答案 2 :(得分: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);