Search code examples
phparrayssortingmultidimensional-arrayarray-merge

How to merge multiple arrays in pairs with PHP?


I get values from a table in a form. I have 2 rows and 2 colums. Each column has 2 values.

I manage to get columns values by rows, I have this array :

array (
  // 1st row
  0 => array (
      0 => 30,
      1 => 34,
      2 => 50,
      3 => 52
  ),
  // 2nd row
  1 => array (
      0 => 34,
      1 => 38,
      2 => 52,
      3 => 54
  )
)

Expected output :

array (
  // 1st row
  0 => array (
      // 1st col
      0 => array (
          0 => 30,
          1 => 34
      ),
      // 2nd col
      1 => array (
          0 => 50,
          1 => 52
      )
  ),
  // 2nd row
  1 => array (
      // 1st col
      0 => array (
          0 => 34,
          1 => 38
      ),
      // 2nd col
      1 => array (
          0 => 52,
          1 => 54
      )
  )
)

I would like to explode each row array in 2 pairs (= 2 colums with 2 values for each one).

I don't know how to do this, maybe with a for loop or with modulus ?


Solution

  • You should make a loop on your array and use array_chunk on each row :

    $array = array (
        array (30,34,50,52),
        array (34,38,52,54)
    );
    
    foreach ( $array as &$row ){
        $row = array_chunk($row, 2);
    }
    
    var_dump($array);