php 根据值从列表数组递增嵌套数组

php increment nested arrray from list array by values

可能是看不到东西, 我有两个数组:

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

$elements =   

 Array
    (
        [0] => 24426
        [1] => 25015
        [2] => 24422
        [3] => 24425
        [4] => 24531
        [5] => 24421
        [6] => 24530
        [7] => 24532
        [8] => 25016
        [9] => 24418
    )

基本上,想法是为 $grid 的每个值和 $elements 的值设置类似的东西。例如 [0] => 3 循环三次会得到 24426,25015,24422。现在问题来了,对于第二个结果 [1] => 2 我只需要获取两个值但不包括迭代的三个 $elements 的先前值。所以基本上在第二次迭代中我会得到 24425,24531.

注意:$grid 值可以是 1 , 2 ,3 ....300...n;

生成的数组应该是这样的:

Array
    (
        [0] => 3,24426
        [1] => 3,25015
        [2] => 3,24422
        [3] => 2,24425
        [4] => 2,24531
        [5] => 3,24421
        [6] => 3,24530
        [7] => 3,24532
        [8] => 2,25016
        [9] => 2,24418
  
  )

编辑:稍微更改了代码以满足所需的输出格式

请考虑此代码。

$grid = [3, 2, 3, 2];
$elements = [24426,25015,24422,24425,24531,24421,24530,24532,25016,24418];

$result = [];
foreach($grid as $take) {
    $org_take = $take;
    while($take-- > 0) {
        if (empty($elements)) {
            throw new Exception('Not enough elements');
        }
        $result[] = sprintf('%d,%d', $org_take, array_shift($elements));
    }
}

print_r($result);

给出结果:

Array ( 
    [0] => 3,24426 
    [1] => 3,25015 
    [2] => 3,24422 
    [3] => 2,24425 
    [4] => 2,24531 
    [5] => 3,24421 
    [6] => 3,24530 
    [7] => 3,24532 
    [8] => 2,25016 
    [9] => 2,24418 
)