比较Array,并显示PHP的差异

时间:2012-01-25 03:36:48

标签: php arrays

我花了很长时间研究如何在数组之间执行此操作但我无法在PHP中获得算法我返回这些结果。

数组#1:

Array DB_ITEMS
(
    [1] => Array
        (
            [item_code] => FO1321
            [item_quantity] => 5
            [item_sellprice] => 18.00
            [found] => 0
        )

    [2] => Array
        (
            [item_code] => HE240
            [item_quantity] => 1
            [item_sellprice] => 22.40
            [found] => 0
        )

)

数组#2:

Array BUY_ITEMS
(
    [1] => Array
        (
            [item_code] => FO1321
            [item_quantity] => 1
            [item_sellprice] => 18.00
            [taken] => 0
        )

    [2] => Array
        (
            [item_code] => EL55
            [item_quantity] => 1
            [item_sellprice] => 8.00
            [taken] => 0
        )

)

我希望此结果采用数组格式:

Array FINAL_RESULT
(
    [1] => Array
        (
            [item_code] => FO1321
            [item_quantity] => -4
            [item_sellprice] => 22.40
            [taken] => 0
        )

    [2] => Array
        (
            [item_code] => HE240
            [item_quantity] => -1
            [item_sellprice] => 22.40
            [taken] => 0
        )

    [3] => Array
        (
            [item_code] => EL55
            [item_quantity] => +1
            [item_sellprice] => 8.00
            [taken] => 0
        )

)

我这样做是为了比较正在修改的现有帐单。 我需要设置它们之间的差异,然后在DB中进行更改。

1 个答案:

答案 0 :(得分:3)

用于计算结果数组值的数学对我没有意义(我怀疑你的帖子中输入的数据可能不对)。

如果我是你,我会使用item_code作为数组键创建关联数组,因此当您进行比较时,您可以在现场更新值。

Array DB_ITEMS
(
    [FO1321] => Array
        (
            [item_code] => FO1321
            [item_quantity] => 5
            [item_sellprice] => 18.00
            [found] => 0
        )

    [HE240] => Array
        (
            [item_code] => HE240
            [item_quantity] => 1
            [item_sellprice] => 22.40
            [found] => 0
        )

)

Array BUY_ITEMS
(
    [FO1321] => Array
        (
            [item_code] => FO1321
            [item_quantity] => 1
            [item_sellprice] => 18.00
            [taken] => 0
        )

    [EL55] => Array
        (
            [item_code] => EL55
            [item_quantity] => 1
            [item_sellprice] => 8.00
            [taken] => 0
        )

)

现在您可以单步执行buy items数组并更新db items数组(未经测试):

foreach ($buyItems as $itemCode => $buyItem) {
    if (array_key_exists($itemCode, $dbItems)) {
        $dbItems[$itemCode]['item_quantity'] =- $buyItem['item_quantity'];
    }
}