Tuesday, January 29, 2008

PHP Multi Dimensional Array Sort

<?php
    /**
    * @desc You really should validate the posted sort direction against a list of valid possibilities.
    *         Options are SORT_ASC, SORT_DESC, etc, as shown in the documentation for array_multisort
    */
    //$sort['direction'] = $_POST['sort_direction'] ? $_POST['sort_direction'] : 'SORT_ASC';
    $sort['direction']='SORT_ASC';
   // $sort['field']       = $_POST['sort_field'] ? $_POST['sort_field'] : 'value';
                    $sort['field']='age';
    $array_to_sort = array();   
    $array_to_sort['TestCase1'] = array('age'=>'24','name'=>'Test1','value'=>'218');
    $array_to_sort['TestCase2'] = array('age'=>'21','name'=>'Test2','value'=>'10');
    $array_to_sort['TestCase3'] = array('age'=>'34','name'=>'Test3','value'=>'64');
   
    /**
    * @desc Build columns using the values, for sorting in php
    */
    $sort_arr = array();
    foreach($array_to_sort AS $uniqid => $row){
        foreach($row AS $key=>$value){
            $sort_arr[$key][$uniqid] = $value;
            
        }
    }
   
    print '<b>Before sorting</b>: <br> <pre>';
    print_r($array_to_sort);
    print '</pre>';
   
    if($sort['direction']){
        array_multisort($sort_arr[$sort['field']], constant($sort['direction']), $array_to_sort);
    }

    print '<b>After sorting</b>: <br> <pre>';
    print_r($array_to_sort);
    print '</pre>';
   
?>

No comments:

Post a Comment