PHP按空值划分数组

时间:2012-07-16 05:35:33

标签: arrays

这是来自输入字段的数组,如下所示

Array(
    [0] =>
    [1] => 737
    [2] => 736
    [3] => 735
    [4] => 
    [5] => 748
    [7] => 744
    [8] => 747
    [9] => 746
    [10] => 
    [11] => 748
    [12] => 747
    [13] => 746
    [14] => 745
    [15] => 744
);

有没有办法将其除以空值并删除空值,如下所示:

Array(
    [0] => Array(
        [0] => 737
        [1] => 736
        [2] => 735
    )
    [1] => Array(
        [0] => 748
        [1] => 744
        [2] => 747
        [3] => 746
    )
    [2] => Array(
        [0] => 748
        [1] => 747
        [2] => 746
        [3] => 745
        [4] => 744
    )
)

1 个答案:

答案 0 :(得分:1)

如果要将数组拆分为子数组,并将“null”值作为分隔符,那么应该完成这项工作:

$newArray = array();
$subArray = null;
for ($i = 0; $i < count($array); $i++) {
    if (!$subArray) $subArray = array();

    $v = $array[$i];
    if ($v) {
        array_push($subArray, $v);
    } else {
        if (count($subArray) > 0) array_push($newArray, $subArray);
        $subArray = null;
    }
}

if ($subArray) array_push($newArray, $subArray);