2011-05-11 65 views
0

我想从pairs.xml文件中显示的最便宜3对数据, 现在我很困惑如何使用条件它。能有人帮我显示xml文件

pairs.xml --- ---------

<pairs> 
    <pair> 
     <name>cups</name> 
     <price>50</price> 
    </pair> 
    <pair> 
     <name>mugs</name> 
     <price>60</price> 
    </pair> 
    <pair> 
     <name>plates</name> 
     <price>40</price> 
    </pair> 
    <pair> 
     <name>spoons</name> 
     <price>10</price> 
    </pair> 
</pairs> 

pairs.php ----------

$xmlFile = "pairs.xml"; 
$doc = DOMDocument::load($xmlFile); 
$pair = $doc->getElementsByTagName("pair"); 
echo "<table border=1><tr><th>Name</th><th>Price</th></tr>"; 
foreach ($pair as $node) { 
    $name = $node->getElementsByTagName("name"); 
    $name = $name->item(0)->nodeValue; 
    $price = $node->getElementsByTagName("price"); 
    $price = $price->item(0)->nodeValue; 

    if() 
     echo "<tr><td>{$name}</td><td>{$price}</td><tr>"; 
} 
+1

您会先循环XML并找到/保存3个最便宜的对,然后执行输出。你不能在一个循环中完成。 – 2011-05-11 20:28:46

+0

@MarcB你应该真的把它作为答案(因为它是答案)。 – 2011-05-11 20:31:49

回答

0
$pairs = array(); 
foreach($pair as $node) 
{ 
    $name = $node->getElementsByTagName("name")->item(0)->nodeValue; 
    $price = $node->getElementsByTagName("price")->item(0)->nodeValue; 
    $pairs[$price] = $name; 
} 
ksort($pairs, SORT_NUMERIC); 
$i = 0; 
foreach($pairs AS $p => $n) 
{ 
    echo("<tr><td>{$n}</td><td>{$p}</td></tr>"); 
    $i++; 
    if($i == 3) 
      break; 
} 
+0

它的工作,感谢 – Anees 2011-05-11 20:49:50

0

我认为this answer可能让你 在正确的轨道上。