拆分数组以获取供应商权重-PHP-
我正在做一个运输计算器,我有一个问题,让我告诉你我有什么,然后我会告诉你我的问题 我的数组和foreach:拆分数组以获取供应商权重-PHP-,php,arrays,virtuemart,Php,Arrays,Virtuemart,我正在做一个运输计算器,我有一个问题,让我告诉你我有什么,然后我会告诉你我的问题 我的数组和foreach: $array = unserialize($_SESSION['__vm']['vmcart']); foreach($array->products as $product){ $price = $product->product_price; $amount = $product->quantity; $length = $product->product
$array = unserialize($_SESSION['__vm']['vmcart']);
foreach($array->products as $product){
$price = $product->product_price;
$amount = $product->quantity;
$length = $product->product_length;
$width = $product->product_width;
$height = $product->product_height;
$weight = $product->product_weight;
$supplier = $product->product_unit;
}
所有的东西都与上面的代码一起工作(这不是我的问题)
我的问题是:
计算器必须从供应商1处获取所有重量,并将其相加,然后对供应商2进行同样的操作(见下文)
例如:
产品1-重量为5kg,由供应商1提供
产品2-重量为2kg,由供应商1提供
产品3-重量为9kg,由供应商2提供
供应商1的重量=至7kg
供应商2的重量=至9kg
同样的事情如果相反的话
现在我尝试的是if语句(见下文),但它所做的只是将每个产品的重量相加
if ($supplier =='S1'){
$s1_total_weight += $product->product_weight;
} if ($supplier =='S2'){
$s2_total_weight += $product->product_weight;
}
echo 'Supplier 1 '.$s1_total_weight.'<br>';
echo 'Supplier 2 '.$s2_total_weight.'<br>';
我是php新手,但我认为这与下面的代码有关,还是我错了?它可以是if语句吗
$product->product_weight
如果您需要更多信息,请告诉我
如果您对此主题有更好的标题,请将其更改为:)
谢谢您的帮助。您好,我得到了一个奇怪的输出-如果我只回显$totalWeight,我会得到“array100arrayarray15310”。如果我将$supplier添加到回显中,它只会添加$key值-有什么想法吗?您的$array->products是否可能并不总是包含“product\u weight”属性的数字?如果它不总是一个数字(但有时是一个数组),则将它们分配给
$weights
数组可以得到这些结果。试着写出来验证一下。(foreach($array->products as$product){var_dump($product->product_weight)}
)嗨,托马斯,如果我只使用我的数组,你给我的上述foreach,我会得到所有产品的重量“string”4.8000(length=6)string“5.2000”(length=6)string“5.0000”(length=6),正如你所看到的-你认为问题出在哪里我仍然会尝试一些东西,看看是否能得到结果;在乞讨时,我用我的阵列替换了它-一切正常-谢谢你这么多人-祝你有一个美好的一天!!
$weights = array();
foreach ($array->products as $product) {
if (isset($weights[$product->product_unit])) {
// there was already some weight for this supplier, just add to it
$weights[$product->product_unit] += $product->product_weight;
}
else {
// first time we encounter this supplier, set weight
$weights[$product->product_unit] = $product->product_weight;
}
}
foreach ($weights as $supplier => $totalWeight) {
echo "Total weight for supplier {$supplier} is {$totalWeight}.";
}
$weights = array();
foreach ($array->products as $product) {
if (isset($weights[$product->product_unit])) {
// there was already some weight for this supplier, just add to it
$weights[$product->product_unit] += $product->product_weight;
}
else {
// first time we encounter this supplier, set weight
$weights[$product->product_unit] = $product->product_weight;
}
}
foreach ($weights as $supplier => $totalWeight) {
echo "Total weight for supplier {$supplier} is {$totalWeight}.";
}