简体   繁体   English

PHP XML总和和按产品分组

[英]Php XML sum and group by product

I have the next xml, and I need to sum by product category. 我有下一个xml,我需要按产品类别进行汇总。 At the moment I have achieved to get the sum of all the products, but I need to sum them by product category. 目前,我已经获得了所有产品的总和,但是我需要按产品类别对它们进行汇总。

    <?xml version="1.0" ?>
    <Result>

    <Record code="198244">
    <AC_LNA ncols="2">
        <row>
        <product>banana</product>
        <qty>1</qty>
        </row>
    </AC_LNA>
    </Record>

    <Record code="198260">
    <AC_LNA ncols="2">
        <row>
        <product>apple</product>
        <qty>7</qty>
        </row>
    </AC_LNA>
    </Record>

    <Record code="198901">
    <AC_LNA ncols="2">
        <row>
        <product>apple</product>
        <qty>3</qty>
        </row>
    </AC_LNA>
    </Record>
    </Result>

This is the code which sum all the products together: 这是将所有产品加在一起的代码:

$xml=new SimpleXMLElement($resp);
$total = 0;
foreach ($xml->Record as $cod) {

foreach ($cod->AC_LNA->row as $lines)
{   
    $qty = $lines->qty; 
    $total += floatval($qty); 
}
}
echo 'Total is: ' . $total.'<br/>';

You need to build an array of quantities for the products... 您需要为产品构建一系列数量...

$xml=new SimpleXMLElement($resp);
$totals = [];
foreach ($xml->Record as $cod) {

    foreach ($cod->AC_LNA->row as $lines)
    {
        $qty = $lines->qty;
        $product = (string)$lines->product;
        if ( !isset($totals[$product]) ){
            $totals[$product]=0;
        }
        $totals[$product] += floatval($qty);
    }
}
print_r($totals);

you need to store value in array 您需要将值存储在数组中

replace your code with 将您的代码替换为

$xml = new SimpleXMLElement($resp);
$total = array();

foreach($xml->Record as $cod)
{
    foreach($cod->AC_LNA->row as $lines)
    {
        $qty = $lines->qty;
        if (isset($total[$lines->product]))
        {
            $total[$lines->product] += floatval($qty);
        }
        else
        {
            $total[$lines->product] = floatval($qty);
        }
    }
}

echo 'Total is: <br/>';
print_r($total);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM