根据检查元素的结果拆分数组

时间:2018-12-20 19:44:44

标签: php arrays

我在PHP中有一个数组,如下所示:

`

Array (
    [0] => Array
        (
            [0] => Some text
            [1] => 6230.C3
        )
    [1] => Array
        (
            [0] => Some text
            [1] => 6230.C3
        )
    [2] => Array
        (
            [0] => 
            [1] => 
        )
    [3] => Array
        (
            [0] => Some text
            [1] => 
        )
    [4] => Array
        (
            [0] => Some text
            [1] => 
        )
    [5] => Array
        (
            [0] => Some text
            [1] => 
        )
    [6] => Array
        (
            [0] => 
            [1] => 
        )
    [7] => Array
        (
            [0] => Some text
            [1] => 
        )
    [8] => Array
        (
            [0] => Some text
            [1] => 
        )
)

`

Array [2]和Array [6]是空数组。请帮助我将数组拆分为三个数组,分别为array1,array2,array3(分别位于Array [2]和Array [6]的位置)。

array1 = [ Array[0], Array[1] ]
array2 = [ Array[3], Array[4], Array[5] ]
Aarray3 = [ Array[7], Array[8] ]

谢谢您的帮助。

1 个答案:

答案 0 :(得分:0)

这比您最初的问题要灵活一些,因为它不仅仅限于3个数组作为单独的变量。以下结果将是一个多维数组,以您想要的方式拆分,但拆分次数不受限制。如果确实是您输入的内容,我可以根据需要重新调整它以使其恰好适合3个变量。

<?php
$final = array();
$counter = 0;
$outerEmpty = false;
foreach($originalArray as $outer) {
    $innerEmpty = true;
    foreach($outer as $inner) {
        if (!empty($inner)) {
            $innerEmpty = false;
            break;
        }
    }
    if (!$innerEmpty)
        $final[$counter][] = $outer;
    else
        $counter++;
}