0

我有一个用 php 读取的 xml 文件。目前我已经加载了 xml,它的内容在表格中很好地显示。目前我正在尝试总结“点”属性的所有值,计算平均值并显示该数字。

任何帮助都会受到欢迎,因为目前我必须将所有这些数字加到计算器上。

xml的基本结构,大大简化:

<data>

...

<season id="1" foo1="bar1" points="1" />  
<season id="2" foo2="bar2" points="2" />
<season id="3" foo3="bar3" points="4" />
<season id="4" foo4="bar4" points="0" /> 

...

</data>

我的PHP:

<?php
$url = "data.xml";
$xml = simplexml_load_file($url);

// loop through xml
foreach($xml->season as $season)
{

...

echo "<tr>";
echo "<td>".$season["id"]."</td>";
echo "</tr>";

...

}
// end ofloop

... 

// don't really know what to do here
// to get to the paragaph below:


<p>Average points = $average_points </p>
?>
4

2 回答 2

3
$total = 0;
$items = 0;

foreach ($xml->season as $season) {

    ...

    $total += $season['points'];
    $items++;

}

if ($items) {
    $average_points = $total / $items;
}
于 2012-04-17T00:02:01.257 回答
2

干得好。

<?php
     $url = "data.xml";
     $xml = simplexml_load_file($url);

     foreach($xml->season as $season)
     {
          echo "<tr>";
          echo "<td>".$season->id."</td>";
          echo "</tr>";
     }

     $count = 0;
     $sum = 0

     foreach($xml->season as $season)
     {
          ++$count;
          $sum += $season->points;
     }

     $average = $sum / $count;
于 2012-04-17T00:07:56.420 回答