Php XML总和和产品分组

时间:2017-07-12 06:39:25

标签: php xml foreach

我有下一个xml,我需要按产品类别求和。目前我已经实现了所有产品的总和,但我需要按产品类别加以总结。

    <?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>

这是将所有产品汇总在一起的代码:

$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/>';

2 个答案:

答案 0 :(得分:0)

您需要为产品构建数量数组......

$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);

答案 1 :(得分:0)

您需要在数组中存储值

替换你的代码
$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);