如何将内部数组与相同的键值合并

时间:2016-11-05 06:48:24

标签: php arrays

请帮助解决此问题 我想改变这个

[UI Testing] => Array
        (
            [0] => Array
                (
                    [0] => 0
                    [1] => 70
                )

            [1] => Array
                (
                    [0] => 40
                    [1] => 0
                )

        )

[UI Testing] => Array
        (
            [0] => Array
                (
                    [0] => 40
                    [1] => 70
                )

        )

感谢。

2 个答案:

答案 0 :(得分:0)

示例

$myArray = array();
$myArray[] = array(0,70);
$myArray[] = array(40,0);

$sumArray = array();

foreach ($myArray as $k=>$subArray) {
  foreach ($subArray as $id=>$value) {

    array_key_exists( $id, $sumArray ) ? $sumArray[$id] += $value : $sumArray[$id] = $value; 
  }
}

print_r($sumArray);

<强>输出:

Array
(
    [0] => 40
    [1] => 70
)

答案 1 :(得分:0)

数组可以filtered删除0值索引,array_reduce删除合并数组。以下示例:

$arr = array('UI Testing' => array( array(0, 70), array(40, 0),) );

$new_arr['UI Testing'] = array_reduce($arr['UI Testing'], function($old, $new) {
    return array_filter($new, function( $v ){ return $v > 0 ? $v : null; }) + $old;
}, []);

print '<pre>';
print_r($new_arr);
print '</pre>';

<强>输出

Array
(
    [UI Testing] => Array
        (
            [0] => 40
            [1] => 70
        )
)