通过分隔符值将php数组拆分为块/部分

时间:2016-09-21 08:46:56

标签: php arrays functional-programming

我编写了以下代码将数组拆分为三个块/部分:

$data = [
    'SECTION1',
    '1',
    '2',
    '3',
    'SECTION2',
    '4',
    '5',
    'SECTION3',
    '6',
    '7',
    '8',
];


$results = [];


foreach ($data as $value) {
    if(strpos($value, 'SECTION') !== false) {
        array_push($results, []);
    } else {
        array_push($results[count($results)-1], $value);
    }
}

结果如下:

$result = [
    [
        '1',
        '2',
        '3'
    ], [
        '4',
        '5'
    ],[
        '6',
        '7',
        '8'
    ]
];

是否有更直观,更易读的方法来使用函数式编程方法转换此数组?

2 个答案:

答案 0 :(得分:0)

$data = [
    'SECTION1',
    '1',
    '2',
    '3',
    'SECTION2',
    '4',
    '5',
    'SECTION3',
    '6',
    '7',
    '8',
];


$cnt = 0;
$result = array();
foreach( $data as $arr ) {
    if( strpos($arr, 'SECTION') !== false) {
        $cnt++;
    } else {
        $result[$cnt][] = $arr;
    }   
}


echo "<pre>";   
print_r($result);

//修订版

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

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

    [3] => Array
        (
            [0] => 6
            [1] => 7
            [2] => 8
        )

)

答案 1 :(得分:0)

再检查一下这是一个人类可读和管理的。

$data = [
    'SECTION1',
    '1',
    '2',
    '3',
    'SECTION2',
    '4',
    '5',
    'SECTION3',
    '6',
    '7',
    '8',
];


$results = [];


foreach ($data as $value) {
    if(strpos($value, 'SECTION') !== false) {
        $results[$value] = array();
    } else {
        $keys = array_keys($results);
        $last = end($keys);
        $results[$last][] = $value;
    }
}
echo '<pre>';
print_r($results);
exit;

输出将为

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

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

    [SECTION3] => Array
        (
            [0] => 6
            [1] => 7
            [2] => 8
        )

)