search

Home  >  Q&A  >  body text

PHP method to increment nested array in list array using value

You may not be able to see anything, I have 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 provide something similar for each value of $grid and the value of $elements. For example [0] => 3 looping three times will get 24426,25015,24422. Now here comes the problem, for the second result [1] => 2 I need to get only two values, but not including the previous values ​​of the three $element iterated over. So basically on the second iteration I'll get 24425,24531.

Note: $grid value can be 1, 2,3...300...n;

The result array should look 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
  
  )

P粉005134685P粉005134685252 days ago391

reply all(1)I'll reply

  • P粉667649253

    P粉6676492532024-03-23 09:05:35

    Edit: Change the code slightly to suit the desired 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 
    )

    reply
    0
  • Cancelreply