簡體   English   中英

如何根據條件`+1`拆分數組?

[英]How to split an array based on the condition `+1`?

如何在序列中的間隙上拆分序列號數組?

序列是n = x + 1其中x是序列中的前一個數字

例如:

$array  = [1,2,3,4,6,7,9,10,11];
$result = [[1,2,3,4], [6,7], [9,10,11]];
$original_array = [1,2,3,4,6,7,9,10,11];
$result_array   = [];


// initialise last value
$last_value = FALSE;                                             


// Loop through each value in original array
foreach($original_array as $value){

    // Check to see if the current value is one more than the current
    // value and that it isn't the first value being checked.
    if($last_value && $value == ++$last_value){
        // Add value to last element of `$result_array` if pre-requisites are TRUE
        $result_array[array_key_last($result_array)][] = $value;
    }
    else{
        // Create a new array in `$result_array` if `if` evaluates to FALSE
        $result_array[] = [$value];
    }


    // Update value ready for next iteration of loop
    $last_value = $value;
}


// Print results
print_r($result_array);

/* Output:

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

    [1] => Array
        (
            [0] => 6
            [1] => 7
        )

    [2] => Array
        (
            [0] => 9
            [1] => 10
            [2] => 11
        )

)

*/

這是一種方法:

<?php
$array = [1, 2, 3, 4, 6, 7, 9, 10, 11];

$i = 0;
$last = null;
foreach($array as $n) {
    if(!is_null($last) && ($n - $last != 1)) {
        $i++;
    }
    $output[$i][] = $n;
    $last = $n;
}

var_dump([[1,2,3,4],[6,7],[9,10,11]] === $output);

Output:

true

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM