PHP将2个数组(multidimentional)与一些计算结合到数组3中

时间:2017-02-28 12:41:59

标签: php arrays multidimensional-array

我正在努力解决以下问题。我有来自2个不同供应商的2个csv文件。我想将两个供应商的库存添加到新的总数组中。

这是Array 1的输出

Array
(
    [0] => Array
        (
            [ARTNUMBER] => 12345
            [STOCK] =>  3
        )
)

这是Array 2的输出

Array
(
    [0] => Array
        (
            [ARTNUMBER] => 12345
            [STOCK] =>  5
        )    
    [2] => Array
        (
            [ARTNUMBER] => 23456
            [STOCK] =>  5
        )
)

新数组应如下所示:

Array
(
    [0] => Array
        (
            [ARTNUMBER] => 12345
            [STOCK] =>  8
        )    
    [2] => Array
        (
            [ARTNUMBER] => 23456
            [STOCK] =>  5
        )
)

我想做两件事:

  • 如果ARTNUMBER在两个阵列中都添加它们。 (阵列1 [ARTNUMBER] + 阵列2 [ARTNUMBER]
  • 如果数组2中的ARTNUMBER不存在 数组1.将其添加到数组中。

有人可以帮我解决一下这个问题吗? (我正在寻找最简单的方法)

1 个答案:

答案 0 :(得分:0)

这应该有效

$array_1[] = array( "ARTNUMBER" => 12345, "STOCK" => 5 );
$array_2[] = array( "ARTNUMBER" => 12345, "STOCK" => 5 );
$array_2[] = array( "ARTNUMBER" => 23456, "STOCK" => 5 );

$data = array();
foreach($array_1 as $key => $value) {
    if(key_exists($value["ARTNUMBER"], $data)) {
        $data[$value["ARTNUMBER"]] += $value["STOCK"];
    }
    else {
        $data[$value["ARTNUMBER"]] = $value["STOCK"];
    }
}
foreach($array_2 as $key => $value) {
    if(key_exists($value["ARTNUMBER"], $data)) {
        $data[$value["ARTNUMBER"]] += $value["STOCK"];
    }
    else {
        $data[$value["ARTNUMBER"]] = $value["STOCK"];
    }
}

$final = array();
foreach($data as $key => $value) {
    $final[] = array( "ARTNUMBER" => $key, "STOCK" => $value );
}

echo "<pre>";
print_r($final);
echo "</pre>";