我有一个产品 xml,其中包含多个价格不同的卖家。在浏览 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 对输出进行排序的方法。
首先,你可能想使用这个结构:
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);
我还没有测试过,但你明白了,我希望它有帮助。