从XML排序价格

时间:2010-07-21 17:31:49

标签: php xml sorting

我正在尝试按照与酒店相关的信息的xml价格对结果进行排序。我希望按价格显示和排序数据,由一个名为minCostStay的值给出,因此ASC和DESC必须这样做。

我正在使用foreach无休止地显示数据。我现在需要做的是按价格asc和desc来理清这些数据。我几乎是一个新手编码,所以任何帮助将不胜感激,特别是如果它是一个简单的例子=)

这或多或少是我正在做的事情:

   $url ="http://www.somedomain.com/cgi/xml/engine/get_data.php?ref=$ref&checkin=$checkin&checkout=$checkout&rval=$rval&pval=$pval&country=$country&city=$city&lg=$lg";


// load SimpleXML
$all = new SimpleXMLElement($url, null, true);

foreach($all as $hotel) // loop through our hotels



{

echo<<

<table width="100%" border=0>   
  <tr>
    <td colspan="2"><h2><a href="{$hotel->rooms->room->bookUrl}">{$hotel->name}<span class="stars" widht="{$hotel->rating}">{$hotel->rating}</span></h2></a></a>
    <p><b>Direccion:</b> <i>{$hotel->address}</p></i>
    </td>
    <td valign="middle"><div align="center"><a href="{$hotel->rooms->room->bookUrl}"><img src="{$hotel->photoUrl}"></div></td>
  </tr>
  <tr>
    <td colspan="2"> $rest...<a href="{$hotel->rooms->room->bookUrl}"><strong>ampliar información</strong></a></td>

    <td  colspan="2" valign="middle" align="right"><div align="center">PRECIO: <h3>{$hotel->currencyCode}{$hotel->minCostOfStay}</h3> </a></div></td>

    </tr>
  <tr>
    <td colspan="2"><div align="center"><a href="{$hotel->rooms->room->bookUrl}"><strong>VER COMENTARIOS, FOTOS Y DETALLES DE ESTE HOTEL</strong></a></div></td>
<td colspan="2"><div align="center">$text</a></div></td>

 </a></div></td>

  </tr>



EOF;


echo '</table>';


}

我听到你了!

提前致谢!

2 个答案:

答案 0 :(得分:2)

1.从XML获取它们(你似乎能够做到这一点) 2.将它们放在一个阵列中 3. sort()数组,如果您的项目更复杂。可能使用usort()

$d =  new SimpleXMLElement('<root>
  <item>
    <price>1234</price>
  </item>
  <item>
    <price>4123</price>
  </item>
  <item>
    <price>3142</price>
  </item>
  <item>
    <price>2431</price>
  </item>
</root>');
$items = array();
foreach($d->item as $item) $items[] = $item;
function _mysort($a,$b){return $a->price - $b->price;}
usort($items,'_mysort');
var_dump($items);

答案 1 :(得分:1)

我最近在一个需要更高级xpath系统的项目中解决了SimpleDOM问题。我非常喜欢它,我认为它可以做你想要的。你可以在这里找到它(文档在源代码下载中捆绑):http://code.google.com/p/simpledom/

你想看看我相信的sortedXPath()方法:

sortedXPath (line 888)

Run an XPath query and sort the result

This method accepts any number of arguments in a way similar to array_multisort()

   1. // Retrieve all <x/> nodes, sorted by @foo ascending, @bar descending
   2. $root->sortedXPath('//x', '@foo', '@bar', SORT_DESC);
   3. 
   4. // Same, but sort @foo numerically and @bar as strings
   5. $root->sortedXPath('//x', '@foo', SORT_NUMERIC, '@bar', SORT_STRING, SORT_DESC);

    * access: public

void sortedXPath (string $xpath)

    * string $xpath: XPath expression