Tuesday, May 17, 2011

multidimensional array sorting in php

Note:- In this post I am sorting multidimensional array by first name if you want to sort by other field then remove first_name and write other field in
array_sort_by_column($people, 'first_name');
Note :- Remove "\" from all places I have added "\" because blogger posting not supported html tags and php opening tag

<\?php

$people = array(
    1 => array(
        'id' => 1,
        'first_name' => 'Kamran',
        'surname' => 'Ahmad',
        'age' => 25,
        'sex' => 'm'
    ),
    2 => array(
        'id' => 2,
        'first_name' => 'Adam',
        'surname' => 'Smith',
        'age' => 18,
        'sex' => 'm'
    ),
    3 => array(
        'id' => 3,
        'first_name' => 'Joe',
        'surname' => 'Bloggs',
        'age' => 23,
        'sex' => 'm'
    ),
    4 => array(
        'id' => 4,
        'first_name' => 'Amy',
        'surname' => 'Jones',
        'age' => 21,
        'sex' => 'f'
    )
);

function array_sort_by_column(&$arr, $col, $dir = SORT_ASC) {
    $sort_col = array();
    foreach ($arr as $key=> $row) {
        $sort_col[$key] = $row[$col];
    }

    array_multisort($sort_col, $dir, $arr);
}

array_sort_by_column($people, 'first_name');
?>
<\table width="500px" cellpadding="0" cellspacing="0" border="1">
    <\tr>
        <\td height="30px" align="center"><\b>ID<\/td>
        <\td height="30px" align="center"><\b>First name<\/b><\/td>
        <\td height="30px" align="center"><\b>Surname<\/b><\/td>
        <\td height="30px" align="center"><\b>Age<\/b><\/td>
        <\td height="30px" align="center"><\b>Sex<\/b><\/td>
  
foreach($people as $peo)
{
    echo "<\tr>";
    echo "<\td height='30px' align='center'>".$peo['id']."<\/td>";
    echo "<\td height='30px' align='center'>".$peo['first_name']."<\/td>";
    echo "<\td height='30px' align='center'>".$peo['surname']."<\/td>";
    echo "<\td height='30px' align='center'>".$peo['age']."<\/td>";
    echo "<\td height='30px' align='center'>".$peo['sex']."<\/td>";
    echo "<\/tr>";
}

?>

<\/table>