phparrayssortingmultidimensional-array

Sort a 2D Array by a column


I have this output:

Array
(
[0] => Array
    (
        [id] => 4
        [username] => bla1
    )

[1] => Array
    (
        [id] => 5
        [username] => bla2
    )

[2] => Array
    (
        [id] => 6
        [username] => bla3
    )

)

How can i sort the 3 arrays inside this outside array by 'username'?

This is what i tried:

if($this->needOrder) {
   $sorted = [];

   foreach($files as $file) {
     $sorted[] = asort($tableFile);
   }

   return $sorted;
 }

$files has the content of the ^above code. The asort() is only for testing if it works. But my return is:

Array
(
  [0] => 1
  [1] => 1
  [2] => 1
)

Solution

  • Use usort()

    $arr = Array(
        array('id' => 4,'username' => 'bla2'),
        array('id' => 5,'username' => 'bla3'),
        array('id' => 6,'username' => 'bla1'),
    );
    
    function custom_sort($a, $b)
    {
        return strnatcmp($a['username'], $b['username']);
    }
    
    usort($arr, "custom_sort");
    
    print '<pre>';
    print_r($arr);
    print '</pre>';
    

    Output:

    Array
    (
    [0] => Array
        (
            [id] => 4
            [username] => bla1
        )
    
    [1] => Array
        (
            [id] => 4
            [username] => bla2
        )
    
    [2] => Array
        (
            [id] => 4
            [username] => bla3
        )
    
    )