Monday, February 23

Sort Multi-dimensional Array by Value using PHP

Take a look at en.wikipedia.org/wiki/Sorting_algorithm for sorting algoritms to be able to sort your data as efficient as possible

<?php
    function aasort (&$array, $key) {
        $sorter=array();
        $ret=array();
        reset($array);
        foreach ($array as $ii => $va) {
            $sorter[$ii]=$va[$key];
        }
        asort($sorter);
        foreach ($sorter as $ii => $va) {
            $ret[$ii]=$array[$ii];
        }
        $array=$ret;
    }
    
    aasort($your_array,"order");
?>

Better alternative

<?php
    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($array, 'order');
?>

No comments:

Post a Comment