【问题标题】:Php XML sum and group by productPHP XML 总和和按产品分组
【发布时间】:2017-07-12 06:39:25
【问题描述】:

我有下一个 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/>';

【问题讨论】:

    标签: php xml foreach


    【解决方案1】:

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

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

    【讨论】:

    • 在获取产品之类的东西时,经常会遗漏的一件事就是将元素转换为字符串。
    【解决方案2】:

    你需要将值存储在数组中

    将您的代码替换为

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

    【讨论】:

      猜你喜欢
      • 2021-06-18
      • 1970-01-01
      • 2020-12-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-23
      • 2020-04-15
      • 1970-01-01
      相关资源
      最近更新 更多