从simplexml排序和数组

时间:2011-11-05 13:54:32

标签: arrays sorting simplexml

我有一个productxml,有多个卖家,价格不同。在我通过simplexml对象并将其放入数组之后,我需要以某种方式对数组进行排序。

循环遍历xml文件:

    foreach($item->Offers->Offer as $offer) {

$trackerprices[]['price'] = $offer->Price;
$trackerprices[]['id_seller'] = $offer->Seller->Id;


}

所以当我输出var_dump $ trackerprices时,它输出:

array(18) { [0]=> array(1) { ["price"]=> object(SimpleXMLElement)#22 (1) { [0]=> string(4) "10.0" } } [1]=> array(1) { ["id_seller"]=> object(SimpleXMLElement)#26 (1) { [0]=> string(16) "1001004002814931" } } [2]=> array(1) { ["price"]=> object(SimpleXMLElement)#16 (1) { [0]=> string(4) "8.29" } } [3]=> array(1) { ["id_seller"]=> object(SimpleXMLElement)#28 (1) { [0]=> string(6) "187216" } } [4]=> array(1) { ["price"]=> object(SimpleXMLElement)#24 (1) { [0]=> string(3) "9.0" } } [5]=> array(1) { ["id_seller"]=> object(SimpleXMLElement)#30 (1) { [0]=> string(6) "441404" } } [6]=> array(1) { ["price"]=> object(SimpleXMLElement)#25 (1) { [0]=> string(4) "9.75" } } [7]=> array(1) { ["id_seller"]=> object(SimpleXMLElement)#32 (1) { [0]=> string(5) "25430" } } [8]=> array(1) { ["price"]=> object(SimpleXMLElement)#27 (1) { [0]=> string(4) "9.95" } } [9]=> array(1) { ["id_seller"]=> object(SimpleXMLElement)#34 (1) { [0]=> string(6) "150362" } } [10]=> array(1) { ["price"]=> object(SimpleXMLElement)#29 (1) { [0]=> string(3) "8.0" } } [11]=> array(1) { ["id_seller"]=> object(SimpleXMLElement)#36 (1) { [0]=> string(6) "502339" } } [12]=> array(1) { ["price"]=> object(SimpleXMLElement)#31 (1) { [0]=> string(3) "9.0" } } [13]=> array(1) { ["id_seller"]=> object(SimpleXMLElement)#38 (1) { [0]=> string(6) "117478" } } [14]=> array(1) { ["price"]=> object(SimpleXMLElement)#33 (1) { [0]=> string(4) "15.0" } } [15]=> array(1) { ["id_seller"]=> object(SimpleXMLElement)#40 (1) { [0]=> string(6) "153058" } } [16]=> array(1) { ["price"]=> object(SimpleXMLElement)#35 (1) { [0]=> string(3) "6.5" } } [17]=> array(1) { ["id_seller"]=> object(SimpleXMLElement)#42 (1) { [0]=> string(6) "402391" } } } 

不,我需要一种按价格ASC排序输出的方法。

我被困在这里,任何人都可以帮助我吗?

提前致谢!

1 个答案:

答案 0 :(得分:0)

首先,您可能想要使用此结构:

foreach($item->Offers->Offer as $offer) {
  $trackerprices[] = array('price' => (float)$offer->Price, 
                           'id_seller' => (string)$offer->Seller->Id);
}

这样,您可以将价格和相应的seller_id保持在一起。所以现在你有一系列价格 - 卖家对,你需要它按每对价格区域排序。您可以使用multisort。这只是一种方法,可能有更有效的解决方案。

foreach($trackerprices as $tp) {
     $sort[] = $tp['price'];
}
array_multisort($sort, SORT_ASC, $trackerprices);

总之,还有3行代码:

$sort = array();
foreach($item->Offers->Offer as $offer) {
  $trackerprices[] = array('price' => (float)$offer->Price, 
                           'id_seller' => (string)$offer->Seller->Id);
  $sort[] = $tp['price'];
}
array_multisort($sort, SORT_ASC, $trackerprices);

我还没有测试过,但你明白了,我希望它有所帮助。