[英]Order Multidimensional Arrays PHP
I have some problem to order an array by a field of this, here i leave the example 我有一些问题,通过这个字段来命令一个数组,这里我留下这个例子
foreach($xml as $site){
echo '<div><a href="'.$site->loc.'">'.$site->loc.'</a>' .$site->padre.'</div>';
}
Some times the filed $site->padre
is empty but i'd like to order by $site->padre
alphabetical i saw example with usort but i don't understand how to work it. 有时候提交的
$site->padre
是空的,但我想通过$site->padre
按字母顺序排序我看到了与usort的例子,但我不明白如何使用它。
Thanks in advance. 提前致谢。
Cheers 干杯
function cmp($a, $b){
return strcmp($a['padre'], $b['padre']);
}
usort($xml, "cmp");
foreach($xml as $site){
echo '<div><a href="'.$site->loc.'">'.$site->loc.'</a>' .$site->padre.'</div>';
}
The cmp function will be called for every element in the array. 将为数组中的每个元素调用cmp函数。 The function must return an integer to determine if $a is more, less or equal to $b.
该函数必须返回一个整数,以确定$ a是否大于,小于或等于$ b。 Specifying ['padre'] in the cmp function will compare that element.
在cmp函数中指定['padre']将比较该元素。
<?php
function alphabetize($a, $b){
# property notation as used in original question
return strcmp($a->padre, $b->padre);
}
$xml = uasort($xml, 'alphabetize');
foreach($xml as $site){
# your code here
}
?>
Alternatively, you can use a lambda function using PHP's create_function()
或者,您可以使用PHP的
create_function()
来使用lambda函数
$xml = uasort($xml, create_function('$a,$b', 'return strcmp($a->padre, $b->padre);'));
Or, if you have PHP >= 5.3 或者,如果你有PHP> = 5.3
$xml = uasort($xml, function($a,$b){ return strcmp($a->padre, $b->padre); });
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.