Php 如何对复杂多维数组进行排序
我需要根据价格对数组进行如下排序:Php 如何对复杂多维数组进行排序,php,sorting,multidimensional-array,Php,Sorting,Multidimensional Array,我需要根据价格对数组进行如下排序: Array ( [SJ] => Array ( [desc] => Junior Suite [solutions] => Array ( [0] => Array ( [code] =>
Array
(
[SJ] => Array
(
[desc] => Junior Suite
[solutions] => Array
(
[0] => Array
(
[code] => BB
[desc] => Bed and Breakfast
[price] => 607.08
[status] => OK
[policy] => 1
[currency] => EU
)
[1] => Array
(
[code] => BB
[desc] => Bed and Breakfast
[price] => 700.80
[status] => OK
[policy] => 1
[currency] => EU
)
)
)
[MZ] => Array
(
[desc] => Doble Deluxe con hidromasaje
[solutions] => Array
(
[0] => Array
(
[code] => BB
[desc] => Bed and Breakfast
[price] => 518.40
[status] => OK
[policy] => 1
[currency] => EU
)
)
)
)
有人能告诉我正确的方法吗?:)
预期结果
Array
(
[MZ] => Array
(
[desc] => Doble Deluxe con hidromasaje
[solutions] => Array
(
[0] => Array
(
[code] => BB
[desc] => Bed and Breakfast
[price] => 518.40
[status] => OK
[policy] => 1
[currency] => EU
)
)
)
[SJ] => Array
(
[desc] => Junior Suite
[solutions] => Array
(
[0] => Array
(
[code] => BB
[desc] => Bed and Breakfast
[price] => 607.08
[status] => OK
[policy] => 1
[currency] => EU
)
[1] => Array
(
[code] => BB
[desc] => Bed and Breakfast
[price] => 700.80
[status] => OK
[policy] => 1
[currency] => EU
)
)
)
)
我需要的是根据价格订购该数组。
因此,如果我有很多解决方案,我需要选择一个价格较低的解决方案,尝试制作另一个包含所有价格的数组,然后用于它。您可以使用PHP函数
usort
,如下所示:
function sortInnerPrice($a, $b) {
if ($a['price'] == $b['price']) {
return 0;
}
return ($a['price'] < $b['price']) ? -1 : 1;
}
// First sort the inner prices
foreach ($test as $key => $val) {
usort($test[$key]['solutions'], 'sortInnerPrice');
}
function cmp($a, $b)
{
$aPrice = $a['solutions'][0]['price'];
$bPrice = $b['solutions'][0]['price'];
if ($aPrice == $bPrice) {
return 0;
}
return ($aPrice < $bPrice) ? -1 : 1;
}
// Then sort by lowest solution price
usort($yourArray, "cmp");
函数排序器价格($a,$b){
如果($a['price']=$b['price']){
返回0;
}
回报($a['price']<$b['price'])?-1:1;
}
//首先对内部价格进行排序
foreach($testas$key=>$val){
usort($test[$key]['solutions','sortInnerPrice');
}
功能cmp($a$b)
{
$aPrice=$a['solutions'][0]['price'];
$b价格=$b['solutions'][0]['price'];
如果($aPrice==$bPrice){
返回0;
}
回报率($aPrice<$bPrice)?-1:1;
}
//然后按最低解决方案价格排序
usort($yourArray,“cmp”);
usort
是一个PHP函数,允许您根据需要对数组进行排序。您创建了一个函数,如果它们相同,则返回0,-1如果您希望$a在$b之前,1如果您希望$a在$b之后。1)您尝试了什么?2) 预期的产量是多少?对不起,那是我的错误。。我有很多解决办法。。在那个例子中只有一个。。但通常有很多解决方案。你希望它如何分类。按平均解决方案?最低的解决方案?最高解决方案?@JackTurky您可能必须首先分别对解决方案价格进行排序,然后按最低解决方案对外部对象进行排序