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('Dale','Steyn','28','South Africa'),
    // Sorting on first element
    $key = 0;
    echo "<pre>";
    echo "</pre>";
    // Sorting on second element
    $key = 1;
    echo "<pre>";
    echo "</pre>";

Sort a multidimensional array in php Sort a multidimensional array in php Reviewed by Altaf Hussain on 11:59 AM Rating: 5

No comments:

Altaf Web. Powered by Blogger.