2012-04-16 12 views
0

私はPHPで読んでいるxmlファイルを持っています。現在、私は読み込まれたXMLとそのコンテンツを表にうまく表示しています。 現在、私は "points"属性のすべての値を合計し、これの平均を計算し、その数値を表示しようとしています。xmlのphp&sum属性値

私は電卓でこれらの数字をすべて追加しなければならないので、歓迎します。

大幅簡体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> 
?> 

答えて

3
$total = 0; 
$items = 0; 

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

    ... 

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

} 

if ($items) { 
    $average_points = $total/$items; 
} 
+0

ありがとうございました!前にstackoverflowを使用したことはありません。 – Dumarest

+0

0で除算します。 – hakre

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;