Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort this array in numeric order using php

I am trying to sort a list of files by their filename.

This is my array:

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
        )

)

As you can see it is now sorted like:

1.2
1.2
1.2
1.1
1.2

How can I sort this the correct way? Like this:

1.1
1.2
1.2
1.2
1.2

I've tried asort like this:

$getfiles = "SELECT * FROM files1 WHERE cat_id = 20";
$getfilescon = $conn->query($getfiles);
while($getfiles[] = $getfilescon->fetch_assoc());
asort($getfiles, $getfiles['filename']);

Or like this:

asort($getfiles['filename']);

Or this:

asort($getfiles[]['filename']);

But nothing is giving the desired result.

like image 293
twan Avatar asked Mar 31 '26 16:03

twan


1 Answers

You need to use usort and create your own sorting priority.
It should look something like this.

function customSort($a, $b) {
    if ($a['filename'] == $b['filename']) {
        return 0;
    }
    return ($a['filename'] < $b['filename']) ? -1 : 1;
}

usort($array, "customSort");

Or if you use PHP 7+

usort($array, function (array $a, array $b) {
    return $a['filename'] <=> $b['filename'];
});
like image 54
Johan Avatar answered Apr 02 '26 04:04

Johan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!