我有两个数组来保存我的产品数据。以下示例。
$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_pcs
和product_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
)
)
答案 0 :(得分:1)
只需循环播放并检查密钥是否为product_id
,transfer_in
和transfer_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