在每个关键元素出现后获取元素 PHP 数组

问题描述 投票:0回答:1

我有一个包含以下元素的数组:

$array = ["START","a","a","a","START","b","b","b","START","c","c","c"];

我只需要在每次出现关键元素“START”后将数组的元素获取到它们自己的数组中:

示例:

$arr[0] = ["a","a","a"];
$arr[1] = ["b","b","b"];
$arr[2] = ["c","c","c"];

然后我可以分解每个单独的数组并根据需要进行处理。

谢谢!

我玩过数组切片等,这似乎是最接近的答案,但无济于事。

php arrays slice
1个回答
0
投票

设计:使用 START 作为分隔符收集每个元素。

实施:

$array = ["START", "a", "a", "a", "START", "b", "b", "b", "START", "c", "c", "c"];
$result = [];
$tempArray = [];

// Loop through each element in the original array
foreach ($array as $element) {
    if ($element === "START") {
        // If we encounter "START" and $tempArray is not empty, add it to $result
        if (!empty($tempArray)) {
            $result[] = $tempArray;
            $tempArray = []; // Reset for the next segment
        }
    } else { // The element was not START, so we add this to the tempArray
        // Collect elements in the temp array
        $tempArray[] = $element;
    }
}

// Don't forget to add the last collected array if it exists
if (!empty($tempArray)) {
    $result[] = $tempArray;
}

// Output the result for verification
print_r($result);
© www.soinside.com 2019 - 2024. All rights reserved.