我正在尝试按文件名对文件列表进行排序。
这是我的数组:
Array
(
[5] =>
[4] => Array
(
[id] => 194
[filename] => 1.2 Organogram company BV.pptx
[name] => undefined
[path] => /home/website/public_html/fileupload/company/organisatie/
[cat_id] => 297
[error] => 0
)
[1] => Array
(
[id] => 195
[filename] => 1.2 VOL VCA R. company 13-12-2024.docx
[name] => undefined
[path] => /home/website/public_html/fileupload/company/organisatie/
[cat_id] => 297
[error] => 0
)
[0] => Array
(
[id] => 196
[filename] => 1.2 MVK- diploma 2016 Piet Schipaanboord.jpg
[name] => undefined
[path] => /home/website/public_html/fileupload/company/organisatie/
[cat_id] => 297
[error] => 0
)
[3] => Array
(
[id] => 200
[filename] => 1.1 Beleidsverklaring 20-09-2018.docx
[name] => undefined
[path] => /home/website/public_html/fileupload/company/organisatie/
[cat_id] => 297
[error] => 0
)
[2] => Array
(
[id] => 201
[filename] => 1.2 Functieomschrijving VGM-functionaris.docx
[name] => undefined
[path] => /home/website/public_html/fileupload/company/organisatie/
[cat_id] => 297
[error] => 0
)
)
您可以看到它现在的排序方式是:
1.2
1.2
1.2
1.1
1.2
如何正确排序呢?像这样:
1.1
1.2
1.2
1.2
1.2
我已经这样尝试过asort
:
$getfiles = "SELECT * FROM files1 WHERE cat_id = 20";
$getfilescon = $conn->query($getfiles);
while($getfiles[] = $getfilescon->fetch_assoc());
asort($getfiles, $getfiles['filename']);
或者这样:
asort($getfiles['filename']);
或者这个:
asort($getfiles[]['filename']);
但是没有任何东西能得到理想的结果。
答案 0 :(得分:4)
您需要使用usort并创建自己的排序优先级。
它应该看起来像这样。
function customSort($a, $b) {
if ($a['filename'] == $b['filename']) {
return 0;
}
return ($a['filename'] < $b['filename']) ? -1 : 1;
}
usort($array, "customSort");
或者,如果您使用的是PHP 7 +
usort($array, function (array $a, array $b) {
return $a['filename'] <=> $b['filename'];
});