如何与PHP成对合并多个数组?

时间:2017-01-19 14:56:05

标签: php arrays sorting multidimensional-array array-merge

我从表格中的表中获取值。我有2行和2列。 每列有2个值。

我设法按行获取列值,我有这个数组:

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

预期产出:

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

我想爆炸2对中的每个行数组(= 2个列,每个列有2个值)。

我不知道怎么做,可能是for循环或模数?

3 个答案:

答案 0 :(得分:1)

使用array_map和array_chunk

.my_input_class {
  padding-right: 1em; // Replace `1em` with the desired amount of padding
}

答案 1 :(得分:0)

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

输出:

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
                )

        )

)

答案 2 :(得分:0)

你应该对你的数组进行循环并在每一行上使用array_chunk:

$array = array (
    array (30,34,50,52),
    array (34,38,52,54)
);

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

var_dump($array);