比较和更新多维数组的元素

时间:2014-08-20 04:55:03

标签: php arrays multidimensional-array

我有一个像下面这样的多维数组。

$test =   Array
        (
            [0] => Array
                (
                    [0] => 38
                    [1] => 3
                    [2] => 7
                    [3] => 2
                    [4] => 232
                    [5] => 1
                    [6] => 58
                )


            [1] => Array
                (
                    [0] => 8
                    [1] => 13
                    [2] => 7
                    [3] => 2
                    [4] => 232
                    [5] => 11
                    [6] => 58
                )


        )

我想推送像

这样的数组元素
$new =   Array
            (
                [0] => 38
                [1] => 3
                [2] => 7
                [3] => 2
                [4] => 232
                [5] => 1
                [6] => 58
            )

所以它应该与多维数组的所有内部数组键元素进行比较,如果它与任何内部数组匹配,如$ test [n] [0] = $ new [0],$ test [n] [ 1] = $ new [1],$ test [n] [2] = $ new [2],$ test [n] [3] = $ new [3],$ test [n] [4] = $ new [4]那么结果应该是这样的。(因为在我们的例子中,$ test [0]匹配)

Array
    (
        [0] => Array
            (
                [0] => 38
                [1] => 3
                [2] => 7
                [3] => 2
                [4] => 232
                [5] => 2     ====> $test[0][5] + $new[5] //updating 1+1 = 2
                [6] => 58
            )


        [1] => Array
            (
                [0] => 8
                [1] => 13
                [2] => 7
                [3] => 2
                [4] => 232
                [5] => 11
                [6] => 58
            )


    )

并且测试阵列正在使用' n'数组。

谢谢你,任何帮助都会得到满足。

1 个答案:

答案 0 :(得分:0)

foreach($test as $key=>$val){
    if($val[0] == $new[0] && $val[1] == $new[1] && $val[2] == $new[2] && $val[3] == $new[3] && $val[4] == $new[4]){
        $val[5] = $val[5] + $new[5];
    }else{
        array_push($test, $new);
    }
}
print_r($test);