2011-11-05 35 views
0

我有一个productxml与多个卖家有不同的价格。我需要通过simplexml对象以某种方式对数组进行排序,并将其放入数组中。从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" } } } 

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

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

在此先感谢!

回答

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); 

我没有测试它,但你的想法,我希望它能帮助。