используя ассоциативный массив - PullRequest
0 голосов
/ 12 мая 2011

Я ищу 2 продукта с меньшими ценами в файле 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>";

1 Ответ

0 голосов
/ 12 мая 2011
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>";    
 }

Может, вот так?

...