一、需求
已知:库存数据,商品数据。 求:库存剩余数据,出库的商品数据,库存不足/不存在的数据 Tips:根据商品编码扣减库存中的商品数量
二、代码
public function test() {
list($stockData, $goodsData) = self::getData();
$errorMsg = [];
$stockOutData = [];
$stockProductName = array_combine(array_column($stockData, 'product_name'), $stockData);
self::stockProcess($goodsData, $stockProductName, $stockOutData, $errorMsg);
echo '<pre>';
echo '库存剩余数据:<br/>';
var_export($stockProductName);
echo '<br/>出库数据:<br/>';
var_export($stockOutData);
echo '<br/>出库失败信息:<br/>';
var_export($errorMsg);
}
public function getData() {
$stockData = [
['product_name' => 'Goods123', 'number' => 10],
['product_name' => 'Goods456', 'number' => 20],
['product_name' => 'Goods789', 'number' => 30],
];
$goodsData = [
['goods_name' => '商品1', 'stock_code' => 'Goods123', 'buy_number' => 7],
['goods_name' => '商品2', 'stock_code' => 'Goods123', 'buy_number' => 7],
['goods_name' => '商品3', 'stock_code' => 'Goods456', 'buy_number' => 7],
['goods_name' => '商品4', 'stock_code' => 'Goods456', 'buy_number' => 7],
['goods_name' => '商品5', 'stock_code' => 'Goods456', 'buy_number' => 7],
['goods_name' => '商品6', 'stock_code' => 'Goods789', 'buy_number' => 30],
['goods_name' => '商品7', 'stock_code' => 'Goods321', 'buy_number' => 3],
];
return [$stockData, $goodsData];
}
public function stockProcess($goodsData, &$stockProductName, &$stockOutData, &$errorMsg) {
foreach ($goodsData as $value) {
$goodsName = $value['goods_name'];
$stockCode = $value['stock_code'];
$buyNumber = $value['buy_number'];
$msg = "商品 [ {$goodsName} ],编码 [ {$stockCode} ]:";
$stockInfo = isset($stockProductName[$stockCode]) ? $stockProductName[$stockCode] : [];
if (!$stockInfo) {
$errorMsg[] = "{$msg}库存不存在";
continue;
}
if ($stockInfo['number'] < $buyNumber) {
$errorMsg[] = "{$msg}库存不足";
continue;
}
$stockProductName[$stockCode]['number'] -= $buyNumber;
$stockOutData[] = [
'product_name' => $stockCode,
'out_number' => $buyNumber
];
}
}
三、打印
库存剩余数据:
array (
'Goods123' =>
array (
'product_name' => 'Goods123',
'number' => 3,
),
'Goods456' =>
array (
'product_name' => 'Goods456',
'number' => 6,
),
'Goods789' =>
array (
'product_name' => 'Goods789',
'number' => 0,
),
)
出库数据:
array (
0 =>
array (
'product_name' => 'Goods123',
'out_number' => 7,
),
1 =>
array (
'product_name' => 'Goods456',
'out_number' => 7,
),
2 =>
array (
'product_name' => 'Goods456',
'out_number' => 7,
),
3 =>
array (
'product_name' => 'Goods789',
'out_number' => 30,
),
)
出库失败信息:
array (
0 => '商品 [ 商品2 ],编码 [ Goods123 ]:库存不足',
1 => '商品 [ 商品5 ],编码 [ Goods456 ]:库存不足',
2 => '商品 [ 商品7 ],编码 [ Goods321 ]:库存不存在',
)
|