Home > Mobile >  php increment nested arrray from list array by values
php increment nested arrray from list array by values

Time:05-08

probably can not see something, I got two arrays:

$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
    )

Basically the idea is to have something like this for every value of $grid the values of $elements. For example [0] => 3 loop three times will give me 24426,25015,24422. Now here comes the catch, for the second result [1] => 2 I need to get only two values but excluding previous values of three $elements, which are iterated. So basically on the second iteration I would get 24425,24531.

NOTICE: $grid values can be 1 , 2 ,3 ....300...n;

The resulting array should be like this:

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
  
  )

CodePudding user response:

EDIT: Changed code slightly to meet required output format

Please consider this code.

$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);

Gives the 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 
)
  • Related