![](/img/trans.png)
[英]How do I sort a multidimensional array with stdClass Objects by values of a key?
[英]Sort multidimensional array of objects
我在stackoverflow上看到了很多示例来对对象的多维数组进行排序
但是它们都无法帮助我对下面给出的对象的多维数组进行排序
SimpleXMLElement Object
(
[request] => SimpleXMLElement Object
(
[address] => test
[citystatezip] => New York
)
[message] => SimpleXMLElement Object
(
[text] => Request successfully processed
[code] => 0
)
[response] => SimpleXMLElement Object
(
[results] => SimpleXMLElement Object
(
[result] => Array
(
[0] => SimpleXMLElement Object
(
[zpid] => 27965224
[links] => SimpleXMLElement Object
(
[homedetails] => test
[graphsanddata] =>test
[mapthishome] => test
[comparables] => test
)
[address] => SimpleXMLElement Object
(
[street] => test
[zipcode] => test
[city] => test
[state] => NY
[latitude] => 29.802114
[longitude] => -95.504244
)
[zestimate] => SimpleXMLElement Object
(
[amount] => 342911
[last-updated] => 11/27/2014
[oneWeekChange] => SimpleXMLElement Object
(
[@attributes] => Array
(
[deprecated] => true
)
)
[valueChange] => 5766
[valuationRange] => SimpleXMLElement Object
(
[low] => 312049
[high] => 373773
)
[percentile] => 0
)
[rentzestimate] => SimpleXMLElement Object
(
[amount] => 5177
[last-updated] => 11/24/2014
[oneWeekChange] => SimpleXMLElement Object
(
[@attributes] => Array
(
[deprecated] => true
)
)
[valueChange] => 370
[valuationRange] => SimpleXMLElement Object
(
[low] => 3417
[high] => 7041
)
)
[localRealEstate] => SimpleXMLElement Object
(
[region] => SimpleXMLElement Object
(
[@attributes] => Array
(
[id] => 271582
[type] => neighborhood
[name] => test
)
[links] => SimpleXMLElement Object
(
[overview] => test
[forSaleByOwner] => test
[forSale] => test
)
)
)
)
[1] => SimpleXMLElement Object
[2] => SimpleXMLElement Object
[3] => SimpleXMLElement Object
..............................
..............................
)
)
)
)
我需要根据密钥数量以降序对上述数组进行排序。 但是问题是数量密钥存在于两个不同的父密钥“ zestimate”和“ rentzestimate”下。
我已经尝试了以下功能,但是没有用:
public function my_comparison($a, $b) {
if ($a->amount == $b->amount) {
return 0;
}
return ($a->amount < $b->amount) ? -1 : 1;
}
有什么帮助吗?
提前致谢
response->results->result
是SimpleXMLElement
对象的数组。 您要基于元素的内部zestimate->amount
属性以降序对数组进行排序。
你必须写一个接受一个比较函数SimpleXMLElement
对象,并且因为你想有一个从大到小的顺序,返回1
,如果zestimate->amount
的第一个对象的属性是小于第二, -1
,如果它是更大和0
,如果是等于:
public function my_comparison(SimpleXMLElement $a, SimpleXMLElement $b) {
if ($a->zestimate->amount == $b->zestimate->amount) {
return 0;
}
return ($a->zestimate->amount < $b->zestimate->amount) ? 1 : -1; // note the signs
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.