如何根据条件对数组进行切片

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

我有一个数组需要在下面的甲酸盐中进行切片。

$arr =[val1,val2,val3,val4,..........];

$result = [
        [ val1, val2, val3 ], /* First 3 elements */
        [ val4, val5, val6 ], /* next 3 elements */
        
        [ val7 ], /* next 1 element */
        [ val8 ], /* next 1 element */
        
        [ val9, val10], /* next 2 elements */
        [ val11, val12 ], /* next 2 elements */ 


        [ val13, val14, val15 ], /* next 3 elements */
        [ val16, val17, val18 ], /* next 3 elements */
        
        [ val19 ], /* next 1 element */
        [ val20 ], /* next 1 element */
        
        [ val21, val22], /* next 2 elements */
        [ val23, val24 ], /* next 2 elements */ and so on...
    
    /*repeat same with next 3,3,1,1,2,2 elements */
        
]

所以我需要转换上面的格式中的数组,因为我的 html 元素显示 3,3,1,1,2,2 格式中的数据。

谢谢

php arrays multidimensional-array
2个回答
1
投票

只需使用 while 循环并迭代数据即可。您可以使用该模式作为可重复计数器。

演示:https://3v4l.org/mnfhP

$pattern = [3, 3, 1, 1, 2, 2];
$data = range(1, 40);

$patternValue = current($pattern);
$patternCount = 0;

$result = [];
$row = [];
while ($value = current($data)) {
    if ($patternCount === $patternValue) {
        $patternValue = next($pattern);
        if (false === $patternValue) {
            $patternValue = reset($pattern);
        }
        $patternCount = 0;
        $result[] = $row;
        $row = [];
    }
    $row[] = $value;
    $patternCount++;
    next($data);
}

echo json_encode($result);

[[1,2,3],[4,5,6],[7],[8],[9,10],[11,12],[13,14,15],[16,17 ,18],[19],[20],[21,22],[23,24],[25,26,27],[28,29,30],[31],[32],[33 ,34],[35,36],[37,38,39]]


0
投票

该解决方案根据所有各个位的总和将原始数据分成块。然后对于每个块 - 它再次将其拆分。

虽然存在嵌套循环,但它是对数据块而不是单个元素进行操作。

$pattern = [3, 3, 1, 1, 2, 2];
$data = range(1, 40);

// How many elements to take each chunk
$length = array_sum($pattern);
// Split the start data into segments
$chunks = array_chunk($data, $length);

$output = [];
foreach ($chunks as $chunk) {
    // For each chunk
    $offset = 0;
    foreach ($pattern as $nextChunkSize) {
        // If no more data, exit loop
        if ($offset > count($chunk)) {
            break;
        }
        // Extract the part of the array for this particular bit
        $output[] = array_slice($chunk, $offset, $nextChunkSize);
        // Move start on by amount of data extracted
        $offset += $nextChunkSize;
    }
}

echo json_encode($output);

给... [[1,2,3],[4,5,6],[7],[8],[9,10],[11,12],[13,14,15],[16,17, 18],[19],[20],[21,22],[23,24],[25,26,27],[28,29,30],[31],[32],[33, 34],[35,36],[37,38,39],[40]]

© www.soinside.com 2019 - 2024. All rights reserved.