[英]How can I sort an alphanumerical Multidimensional Array in php?
I have some json filenames in an multidimensional array, created like this: $files[] = array("name" => $file, "type" => "json")
that I want to sort ascending like this:我在多维数组中有一些 json 文件名,创建如下:
$files[] = array("name" => $file, "type" => "json")
我想像这样升序排序:
1.File
2.File
3.File
10.File
11.File
If I order them using php sort($files)
function they will be ordered like this:如果我使用 php
sort($files)
function 订购它们,它们的订购方式如下:
1.File
10.File
11.File
2.File
3.File
If however I use natsort($files)
that quote: orders alphanumeric strings in the way a human being would ( php.net ) , I get a total mess:但是,如果我使用
natsort($files)
引用:以人类( php.net )的方式订购字母数字字符串,我会一团糟:
3.File
2.File
10.File
1.File
11.File
Is there some better approach to order an array using php functions?有没有更好的方法来使用 php 函数订购阵列? Or do I have to build a custom sorting function.
还是我必须建立一个自定义排序 function。 The server is running PHP 7.0.
服务器正在运行 PHP 7.0。
You use multidimensional array, as you can see PHP have an error ( Array to string conversion
), you need to use usort
for that task like:您使用多维数组,如您所见 PHP 有一个错误(
Array to string conversion
),您需要使用usort
来完成该任务,例如:
$array = array(
array("name"=>'1.File', "type" => "json"),
array("name"=>'2.File', "type" => "json"),
array("name"=>'3.File', "type" => "json"),
array("name"=>'10.File', "type" => "json"),
array("name"=>'11.File', "type" => "json"),
);
usort($array, function($a, $b) {
return ($a['name'] > $b['name'])
? 1
: ($a['name'] < $b['name'])
? -1
: 0;
});
print_r($array);
Reference:参考:
As @u_mulder suggest strnatcasecmp
will improve the code like:正如@u_mulder 建议的那样,
strnatcasecmp
将改进代码,例如:
usort($array, function($a, $b) {
return strnatcasecmp($a['name'], $b['name']);
});
Reference:参考:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.