Sort a multidimensional array in php

Use this code to sort a multidimensional array. You need the array and the element position on which the array has to be sorted.

Suppose you have to sort the array by the first element, before calling the function set the $key variable to 0, by second element set it to 1 and so on.

Php function usort() is used here which sorts an array by values using a user-defined comparison function. The comparison function used here is compare(). Look at the given code.

    function sort_array($array){
     usort($array, 'compre');
     return $array;
    }
    
    function compre($a, $b){
     global $key;
     return strcmp($a[$key], $b[$key]);
    }


Example : How to call the function

    $array = array(
      array('Chris','Gayle','34','West Indies'),
      array('Ricky','Ponting','35','Australia'),
      array('Dale','Steyn','28','South Africa'),
      array('Virat','Kohli','22','India'),
      array('Stuart','Broad','24','England'),
      array('Daniel','Vettori','38','Newzealand')
      );
    
    // Sorting on first element
    
    $key = 0;
    $result=sort_array($array);
    
    echo "<pre>";
    print_r($result);
    echo "</pre>";
    
    // Sorting on second element
    
    $key = 1;
    $result=sort_array($array);
    
    echo "<pre>";
    print_r($result);
    echo "</pre>";

Sort a multidimensional array in php Sort a multidimensional array in php Reviewed by JS Pixels on September 19, 2012 Rating: 5

No comments:

Altaf Web. Powered by Blogger.