Php 当某些值本身是数组时,对数组进行排序
我有一个数组,看起来像:Php 当某些值本身是数组时,对数组进行排序,php,arrays,Php,Arrays,我有一个数组,看起来像: array(5) { ["title"]=> string(22) "http://example.com/288" ["title2"]=> string(22) "http://example.com/290" ["title3"]=> string(22) "http://example.com/284" ["title4"]=> array(2) { [0]=> string(22)
array(5) {
["title"]=>
string(22) "http://example.com/288"
["title2"]=>
string(22) "http://example.com/290"
["title3"]=>
string(22) "http://example.com/284"
["title4"]=>
array(2) {
[0]=>
string(22) "http://example.com/275"
[1]=>
string(22) "http://example.com/274"
}
["title5"]=>
array(2) {
[0]=>
string(22) "http://example.com/292"
[1]=>
string(22) "http://example.com/291"
}
}
我想对数组进行排序,只要我的值本身不是数组,它就可以正常工作。如果iarsort($array)代码>它给出以下信息:
array(5) {
["title5"]=>
array(2) {
[0]=>
string(22) "http://example.com/292"
[1]=>
string(22) "http://example.com/291"
}
["title4"]=>
array(2) {
[0]=>
string(22) "http://example.com/275"
[1]=>
string(22) "http://example.com/274"
}
["title2"]=>
string(22) "http://example.com/290"
["title"]=>
string(22) "http://example.com/288"
["title3"]=>
string(22) "http://example.com/284"
}
但我希望是这样:
array(5) {
["title5"]=>
array(2) {
[0]=>
string(22) "http://example.com/292"
[1]=>
string(22) "http://example.com/291"
}
["title2"]=>
string(22) "http://example.com/290"
["title"]=>
string(22) "http://example.com/288"
["title3"]=>
string(22) "http://example.com/284"
["title4"]=>
array(2) {
[0]=>
string(22) "http://example.com/275"
[1]=>
string(22) "http://example.com/274"
}
}
因此,基本上我想在url保留键中从高到低对数组进行排序,但当我进行排序时,它会将数组中的值放在列表的顶部,而不管url中的数字是多少
您应该使用并实现自己的比较功能,也许:
uasort($arr, function($a, $b) {
return strcmp(is_array($a) ? $a[0] : $a, is_array($b) ? $b[0] : $b);
});
我认为你的要求没有明确规定。对于以下数组,排序应该如何进行
$myarray = array(
'title1' => array( '1000', '800' ),
'title2' => 900
);
您的示例似乎假设这种情况是不可能的,并且内部数组中的所有值都不能被该数组之外的任何值中断,是这样吗
如果是这样,您应该按照@Dor Shemer的建议使用自定义排序,但是使用uasort而不是usort来维护键值关联。函数cmp($a,$b){return strcmp(is_array($a)$a[0]:$a,is_array($b)}uasort($b[0]:$b);}代码>是我最后使用的,你的确切代码为我抛出了一个错误。非常好用,谢谢@user575594您的PHP版本是什么?保存键的uasort()
要点很重要。谢谢,我刚才才明白你的答案。我想是的,内部数组可能会被外部值中断,但是内部数组值必须始终保持在一起,因为它们有一个公共键。我想弄清楚这会如何影响分类。