[英]sort associative array by key value
I try to sort my array by "delais_livraison" by DESC in php but i dont know how i can do that 我试图用DESC在php中按“ delais_livraison”对我的数组进行排序,但是我不知道该怎么做
In the first level I expected to have in first Etoile => 25
and then Feuillage => 10
在第一个级别中,我期望首先是Etoile => 25
,然后是Feuillage => 10
Array
(
[A] => Array
(
[0] => Array
(
[Feuillage] => Array
(
[delais_livraison] => 10
)
)
[1] => Array
(
[Étoiles] => Array
(
[delais_livraison] => 25
)
)
)
[B] => Array
(
[0] => Array
(
[Grenouillère] => Array
(
[delais_livraison] => 7
)
)
[1] => Array
(
[Chaussons] => Array
(
[delais_livraison] => 0
)
)
)
)
Edit : this how my array has been build pastebin 编辑:这是我的数组如何建立pastebin
Just try with: 只需尝试:
$data = array(
'A' => array(
array('Feuillage' => array('delais_livraison' => 10)),
array('Étoiles' => array('delais_livraison' => 25)),
),
'B' => array(
array('Grenouillère' => array('delais_livraison' => 7)),
array('Chaussons' => array('delais_livraison' => 0)),
),
);
foreach ($data as &$group) {
usort($group, function($itemA, $itemB){
$a = current($itemA)['delais_livraison'];
$b = current($itemB)['delais_livraison'];
if ($a == $b) return 0;
return ($a > $b) ? -1 : 1;
});
}
Output: 输出:
array (size=2)
'A' =>
array (size=2)
0 =>
array (size=1)
'Étoiles' =>
array (size=1)
'delais_livraison' => int 25
1 =>
array (size=1)
'Feuillage' =>
array (size=1)
'delais_livraison' => int 10
'B' => &
array (size=2)
0 =>
array (size=1)
'Grenouillère' =>
array (size=1)
'delais_livraison' => int 7
1 =>
array (size=1)
'Chaussons' =>
array (size=1)
'delais_livraison' => int 0
Solution uses anonymous function that has been introduced in PHP 5.3.0
. 解决方案使用PHP 5.3.0
引入的匿名函数 。 For older versions just create a function and specify it in usort
function: 对于旧版本,只需创建一个函数并在usort
函数中指定它:
function my_sort_function($itemA, $itemB){
// ...
}
usort($group, 'my_sort_function');
Since your array has two levels, how do you want to manage a global sort ? 由于您的数组有两个级别,因此如何管理全局排序? Do you want to do a sort for each sub array ( A, B, ...) ? 是否要对每个子数组(A,B,...)进行排序?
In this case the approach will be to use function uksort for each sub array (A and B) and define your own compare function to compare delais_livraison values. 在这种情况下,方法是对每个子数组(A和B)使用uksort函数,并定义自己的比较函数以比较delais_livraison值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.