合并两个数组值

时间:2018-04-19 14:39:21

标签: php arrays

我该如何制作这个数组:

[EnableCors(origins: "**http:/...(Here the website you want to enter)**", headers: "*", methods: "*")] 

看起来如下所示,其中[1]和[2]已基于具有相同的Array ( [0] => Array ( [id] => 3412341233214 [number] => 21000 ) [1] => Array ( [id] => 12121212121212 [number] => 18000 ) [2] => Array ( [id] => 12121212121212 [number] => 17000 ) ) 合并为单个数组,并且id已添加到一起。

number

1 个答案:

答案 0 :(得分:0)

创建一个$tmp数组,在其中存储number属性。

仅在id尚未使用时才存储:

if(!isset($tmp[$obj['id']]))

使每个值唯一

之后,使用$tmp号码计算$array号码。

$tmp[$obj['id']]['number'] += $obj['number'];

<强> https://3v4l.org/UMJ4p

$array = array(
    0 => array(
        "id" => 3412341233214,
        "number" => 21000    
    ),
    1 => array(
        "id" => 12121212121212,
        "number" => 18000    
    ),
    2 => array(
        "id" => 12121212121212,
        "number" => 17000    
    )
);

$tmp = Array();

foreach($array as $obj) {
    if(!isset($tmp[$obj['id']])) {
        $tmp[$obj['id']] = array_merge(Array('number'=>1),$obj);
        continue;
    }
    $tmp[$obj['id']]['number'] += $obj['number'];
}

print_r(array_values($tmp));

以下代码会生成

(
    [0] => Array
        (
            [number] => 21000
            [id] => 3412341233214
        )

    [1] => Array
        (
            [number] => 35000
            [id] => 12121212121212
        )

)