Driver Driver - 1 month ago 6
PHP Question

Add sorting to an array in php

I need some help in table sorting in PHP. This command:

print_r($pieces);


prints me this:

Array (
[0] => John
[1] => 22
[2] => blue
[3] => offline
)

Array (
[0] => Ann
[1] => 19
[2] => 897505034
[3] => red
[4] => online
)

Array (
[0] => Mike
[1] => 31
[2] => 897505034
[3] => yellow
[4] => online
)


And then I fill the table with this records.

echo "<tr>";
echo "<td>" . $pieces[0] . "</td>";
echo "<td>" . $pieces[1] . "</td>";
echo "<td>" . $pieces[2] . "</td>";
echo "<td>" . $pieces[3] . "</td>";
echo "<td>" . $pieces[4] . "</td>";
echo "</tr>";

John,22,blue,offline
Ann,19,897505034,red,online
Mike,31,897505034,yellow,online


I don't know how to change the order of filling the table by sorting the items by age for example:

Ann,19,897505034,red,online
John,22,blue,offline
Mike,31,897505034,yellow,online

Answer

Make use of Usort

Do like this

 <?php
$pieces=array(array (
    0 => 'John',
    1 => 22,
    2 => 'blue',
    3 => 'offline'
),

    array (
        0 => 'Ann',
        1 => 19,
        2 => 897505034,
        3 => 'red',
        4 => 'online'
    ),

    array (
        0 => 'Mike',
        1 => 31,
        2 => 897505034,
        3 => 'yellow',
        4 => 'online'
    ));

usort($pieces,function($a,$b){ return $a[1]<$b[1]?-1:$a[1]!=$b[1];});


foreach($pieces as $arr){
foreach($arr as $v){
    echo  $v." ";
}
echo "\n";

}

DEMO

OUTPUT

Ann 19 897505034 red online 
John 22 blue offline 
Mike 31 897505034 yellow online