【问题标题】:Split array to get supplier weight - PHP -拆分数组以获取供应商权重 - PHP -
【发布时间】:2013-08-15 12:40:31
【问题描述】:

我正在使用运费计算器,但遇到了问题,让我告诉你我有什么,然后我会告诉你我的问题,

我的数组和foreach:

$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 执行相同的操作(见下文)

例子:

Product1 - 重量为 5kg,来自供应商 1

Product2 - 重量为 2kg,来自供应商 1

产品 3 - 重量为 9 公斤,来自供应商 2

供应商 1 的重量 = 至 7kg

供应商 2 的重量 = 至 9 公斤

反之亦然,

现在我尝试的是一个 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>';

我使用以下代码获取供应商编号(S1 = 供应商 1 - S2 = 供应商 2),

$supplier = $product->product_unit;

我是 php 新手,但我认为这与下面的代码有关,还是我错了?可以是if语句吗?

$product->product_weight

如果您需要更多信息,请告诉我,

如果您对此主题有更好的标题,请更改它:)

感谢您的帮助。

【问题讨论】:

    标签: php arrays virtuemart


    【解决方案1】:
    $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}.";
    }
    

    【讨论】:

    • 嗨,我得到一个奇怪的输出 - 如果我只回显 $totalWeight 我得到“Array1001100ArrayArrayArray15315310”如果我将 $supplier 添加到回显它只是添加 $key 值 - 有什么想法吗?
    • 您的 $array->products 是否可能并不总是包含 'product_weight' 属性的数字?如果它不总是一个数字(但例如有时是一个数组),将它们分配给$weights 数组可以给出这些结果。试着写出来验证一下。 (foreach ($array-&gt;products as $product) { var_dump($product-&gt;product_weight); })
    • 嗨 Tomas,如果我只使用我的数组和上面你给的 foreach 我得到所有产品的重量 "string '4.8000' (length=6) string '5.2000' (length=6) string '5.0000 ' (length=6)" 正如你所看到的 - 你认为问题是什么? - 我还是会尝试一些东西,看看能不能得到结果。
    • Tomas 问题是当我测试你的代码时我没有添加 $weights = array();在乞求时,我用我的阵列替换了它 - 一切正常 - 非常感谢你 - 祝你有美好的一天!
    猜你喜欢
    • 2022-07-10
    • 1970-01-01
    • 2017-11-30
    • 2019-02-05
    • 1970-01-01
    • 2019-08-19
    • 1970-01-01
    • 2019-09-18
    • 1970-01-01
    相关资源
    最近更新 更多