array_merge& in_array不是我需要的

时间:2018-02-03 16:02:06

标签: php

我有这样的数组;

$array = array(
     array('id' => 1, 'amount' => 104, 
     array('id' => 46, 'amount' => 200,
     array('id' => 1004, 'amount' => 200
);

和另一个这样的数组;

$array2 = array(
     array('id' => 206, 'amount' => 50, 
     array('id' => 1, 'amount' => 96,
     array('id' => 88, 'amount' => 2
);

如何添加检查' id'在array2中存在于$ array中。如果它的数量为' $ array2到$ array的内容,如果它不存在,则将id和amount附加到$ array的末尾。我希望输出结果如下所示:

array {
     [0] id = 1  amount = 200
     [1] id = 46 amount = 200
     [2] id = 1004 amount = 200
     [3] id = 206 amount = 50
     [4] id = 88 amount = 2
}

我尝试过使用array_merge和in_array,但似乎无法理解它的工作原理。

1 个答案:

答案 0 :(得分:0)

你可以尝试这样的事情:

foreach ($array as $key => $value) {
    $found = false ;
    foreach ($array2 as $key2 => $value2) {
        if ($value2['id'] == $value['id']) {
            $array2[$key2]['amount'] += $value['amount'];
            $found = true;
            break;
        }
    }
    if (!$found) {
        $array2[] = $value ;
    }
}

print_r($array2);

输出:

Array
(
    [0] => Array
        (
            [id] => 206
            [amount] => 50
        )

    [1] => Array
        (
            [id] => 1
            [amount] => 200
        )

    [2] => Array
        (
            [id] => 88
            [amount] => 2
        )

    [3] => Array
        (
            [id] => 46
            [amount] => 200
        )

    [4] => Array
        (
            [id] => 1004
            [amount] => 200
        )

)

编辑评论后,更新代码并进行最终检查以删除重复的行:

foreach ($array as $key => $value) {
    $found = false ;
    foreach ($array2 as $key2 => $value2) {
        if ($value2['id'] == $value['id']) {
            $array2[$key2]['amount'] += $value['amount'];
            $found = true;
            break;
        }
    }
    if (!$found) {
        $array2[] = $value ;
    }
}


$final = [];
foreach ($array2 as $key1 => $value) {
    $found = false ;
    foreach ($final as $key2 => $value2) {
        if ($value2['id'] == $value['id']) {
            $final[$key2]['amount'] += $value['amount'];
            $found = true;
            break;
        }
    }
    if (!$found) {
        $final[] = $value ;
    }
}

var_dump($final) ;