早上好,对于库存库存,我想在销售汽车时自动更新。我有2x二维数组:
$array_purchase = array(
array(
'Name' => 'Mercedes',
'Purchase' => 10
),
array(
'Name' => 'BMW',
'Purchase' => 20
),
array(
'Name' => 'FIAT',
'Purchase' => 30
)
);
$array_sales = array(
array(
'Name' => 'Mercedes',
'Purchase' => 5
),
array(
'Name' => 'BMW',
'Purchase' => 10
)
);
我尝试使用它,但对我不起作用:
foreach($array_sales as $sName => $sSold){
if(isset($array_purchase[$sName])){
$array_purchase[$sName] - $sSold;
}
}
结果应该像
梅赛德斯:5x (10-5)
菲亚特:30x (30 - 0)
宝马:10x (20 - 10)
任何帮助将不胜感激。
提前感谢您的时间。
答案 0 :(得分:1)
foreach($array_purchase as $key => $value){
if(isset($array_sales[$key]['Purchase'])){
echo($array_purchase[$key]['Name']." ".($array_purchase[$key]['Purchase'] - $array_sales[$key]['Purchase']));
echo("<br />");
} else {
echo($array_purchase[$key]['Name']." ".$array_purchase[$key]['Purchase']);
echo("<br />");
}
};
此代码可以进行大量优化,但它可以让您了解如何循环访问数据。
答案 1 :(得分:1)
如果您希望以这种方式保持数据结构,那么这就是您的解决方案:
<强>代码:强>
foreach ( $array_sales as $keySales => $sales ) {
foreach ( $array_purchase as $keyPurchase => &$purchase ) {
if ( $purchase[ 'Name' ] == $sales[ 'Name' ] ) {
$purchase[ 'Purchase' ] -= $sales[ 'Purchase' ];
//break the 2nd foreach
break;
}
}
//unset the reference!
unset ( $purchase );
}
print_r( $array_purchase );
结果:
Array
(
[0] => Array
(
[Name] => Mecedes
[Purchase] => 5
)
[1] => Array
(
[Name] => BMW
[Purchase] => 10
)
[2] => Array
(
[Name] => FIAT
[Purchase] => 30
)
)
你对PHP中的数组缺乏一点了解,网上有一些很好的例子,http://php.net/manual/en/language.types.array.php,只是google一些。
答案 2 :(得分:0)
您可以将多维数组转换为单维数组,然后对购买数组执行简单的减法操作:
$array_purchase = transformToSingleDimension($array_purchase);
$array_sales = transformToSingleDimension($array_sales);
$result = arraySubstract($array_purchase, $array_sales);
var_dump($result);
function transformToSingleDimension($array)
{
return array_reduce($array, function ($carry, $item) {
$carry[$item['Name']] = $item['Purchase'];
return $carry;
}, array());
}
function arraySubstract($array1, $array2)
{
foreach ($array1 as $key => &$value) {
if (isset($array2[$key])) {
$value -= $array2[$key];
}
}
return $array1;
}
结果将是:
array(3) { ["Mecedes"]=> int(5) ["BMW"]=> int(10) ["FIAT"]=> int(30) }