2011-05-12 74 views
0

我在soap.xml文件中搜索價格較低的兩種產品,我使用了 以下代碼,但它只顯示產品名稱和價格,但我希望這兩種產品的全部細節(產品名稱,價格,數量, 可用性)。 任何人可以幫助我使用關聯數組

soap.xml文件:

<products> 
<product> 
<proname>Lux soap</proname> 
<quantity>5</quantity> 
<price>10</price> 
<available>yes<available> 
</product> 
<product> 
<proname>Pamela Soap</proname> 
<quantity>5</quantity> 
<price>5</price> 
<available>yes<available> 
</product> 
<product> 
<proname>Camery Soap</proname> 
<quantity>5</quantity> 
<price>15</price> 
<available>yes<available> 
</product> 
</products> 

php文件:

  $doc= DOMDocument::load("soaps.xml"); 
     $product = $doc->getElementsByTagName("product"); 
     echo "<table><tr><th>Product_name</th><th>Quantity</th><th>Price</th><th>Available</th></tr>";  
     $prod=array(); 
     foreach($product as $node) 
     { 
     $proname = $node->getElementsByTagName("proname"); 
     $proname = $proname->item(0)->nodeValue; 
     $quantity = $node->getElementsByTagName("quantity"); 
     $quantity = $quantity->item(0)->nodeValue; 
     $price = $node->getElementsByTagName("price"); 
     $price = $price->item(0)->nodeValue; 
     $availble = $node->getElementsByTagName("available"); 
     $available= $available->item(0)->nodeValue; 

     $prod[$price]=$proname; 

     } 

     ksort($prod, SORT_NUMERIC); 
     $a = 0; 
     foreach($prod AS $pri => $nam) 
     {  
     echo"<tr><td>{$nam}</td><td>{$pri}</td></tr>";  
     $i++;  
     if($i == 2)   
     break; 
     } 

     echo "</table>"; 

回答

0
foreach($product as $node) 
{ 
    $proname = $node->getElementsByTagName("proname"); 
    $proname = $proname->item(0)->nodeValue; 
    $quantity = $node->getElementsByTagName("quantity"); 
    $quantity = $quantity->item(0)->nodeValue; 
    $price = $node->getElementsByTagName("price"); 
    $price = $price->item(0)->nodeValue; 
    $availble = $node->getElementsByTagName("available"); 
    $availble = $available->item(0)->nodeValue; 

    $prod[$price]= array($proname, $quantity, $price, $availble); 

} 
ksort($prod, SORT_NUMERIC); 
$prod = array_slice($prod,0,2); 
foreach($prod AS $pri => $nam) 
{  
    echo"<tr><td>{$nam[0]}</td><td>{$nam[1]}</td><td>{$nam[2]}</td><td>{$pri}</td></tr>";  
} 

也許這樣嗎?