有条件地减去数组

时间:2017-11-22 06:58:48

标签: php arrays foreach

我有两个数组来保存我的产品数据。以下示例。

$transfer_in数组

  Array
    (
    [0] => Array
        (
            [product_id] => 2
            [product_qty] => 32
            [product_pcs] => 0
        )
    [1] => Array
        (
            [product_id] => 3
            [product_qty] => 353
            [product_pcs] => 2
        )
    [2] => Array
        (
            [product_id] => 5
            [product_qty] => 11
            [product_pcs] => 1
        )
)

$transfer_out数组

Array
(
    [0] => Array
        (
            [product_id] => 5
            [product_qty] => 1
            [product_pcs] => 1
        )
)

现在我必须用产品的特定product_id减去两个数组。 如果两个数组中的product_id相同/存在,则减去它。 $transfer_in['product_qty'] - $transfer_out['product_qty']$transfer_in['product_pcs'] - $transfer_out['product_pcs']

如何在两个阵列上用相同的product_qty减去每个product_pcsproduct_id并将它们作为一个数组放置?

预期输出应为:

$output = 
Array
    (
    [0] => Array
        (
            [product_id] => 2
            [product_qty] => 32
            [product_pcs] => 0
        )
    [1] => Array
        (
            [product_id] => 3
            [product_qty] => 353
            [product_pcs] => 2
        )
    [2] => Array
        (
            [product_id] => 5
            [product_qty] => 10
            [product_pcs] => 0
        )
)

1 个答案:

答案 0 :(得分:1)

只需循环播放并检查密钥是否为product_idtransfer_intransfer_out product_id是否相等

<强>解决方案

$transfer_in = array
    (
    0 => array
        (
            'product_id' => 2,
            'product_qty' => 32,
            'product_pcs' => 0
        ),
    1 => array
        (
            'product_id' => 3,
            'product_qty' => 353,
            'product_pcs' => 2
        ),
    2 => array
        (
            'product_id' => 5,
            'product_qty' => 11,
            'product_pcs' => 1
        )
);


$transfer_out = array
(
    0 => array
        (
            'product_id'=> 5,
            'product_qty' => 1,
            'product_pcs' => 1
        )
);

foreach($transfer_in as $in_key => $in_product){
    foreach($transfer_out as $out_key => $out_product){

        if( $out_key == 'product_id' && $in_product['product_id'] == $out_product['product_id']){
            $transfer_in[$in_key]['product_qty'] = $in_product['product_qty'] - $out_product['product_qty'];
            $transfer_in[$in_key]['product_pcs'] = $in_product['product_pcs'] - $out_product['product_pcs'];
        }
    }
}

//Print Result
foreach($transfer_in as $in_key => $in_product){
    echo $in_key . '<br />';
    foreach($in_product as $out_key => $out_product){
        echo $out_key . ' = ' . $out_product . '<br />';
    }
    echo '<br />';
}

<强>输出

0
product_id = 2
product_qty = 32
product_pcs = 0

1
product_id = 3
product_qty = 353
product_pcs = 2

2
product_id = 5
product_qty = 10
product_pcs = 0