Eve
Eve

Reputation: 806

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 ?

Upvotes: 0

Views: 309

Answers (3)

LF-DevJourney
LF-DevJourney

Reputation: 28529

use array_map, and array_chunk

array_map(function($v){return array_chunk($v, 2);), $array);

Upvotes: 1

Yoleth
Yoleth

Reputation: 1272

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

Upvotes: 0

labue
labue

Reputation: 2623

With array_chunk:

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

foreach ($array as &$a) {
    $a = array_chunk($a, 2);
}

print_r($array);

Outputs:

Array
(
    [0] => Array
        (
            [0] => Array
                (
                    [0] => 30
                    [1] => 34
                )

            [1] => Array
                (
                    [0] => 50
                    [1] => 52
                )

        )

    [1] => Array
        (
            [0] => Array
                (
                    [0] => 34
                    [1] => 38
                )

            [1] => Array
                (
                    [0] => 52
                    [1] => 54
                )

        )

)

Upvotes: 0

Related Questions