phparrayssortingmultidimensional-array

Sort a 2d Array by a column


I have the following array.

Array  (
        [0] => Array(
              [vendorid] => 36
              [vendorname] => Nothin' But A Muffin
              [vendorfriendlyname] => nothin-but-a-muffin
          )
        [1] => Array(
              [vendorid] => 52
              [vendorname] => Montalto Olive Grove
              [vendorfriendlyname] => montalto-olive-grove
          )
        [2] => Array(
              [vendorid] => 44
              [vendorname] => Kuki Kids
              [vendorfriendlyname] => kuki-kids
          )
        [3] => Array(
              [vendorid] => 47
              [vendorname] => pasApas
              [vendorfriendlyname] => pasapas
          )
        [4] => Array(
              [vendorid] => 89
              [vendorname] => Organic Family
              [vendorfriendlyname] => organic-family
          )
    )

I need to trasform the above array into the following

Array  (
        [0] => Array(
              [vendorid] => 44
              [vendorname] => Kuki Kids
              [vendorfriendlyname] => kuki-kids
          )
        [1] => Array(
              [vendorid] => 52
              [vendorname] => Montalto Olive Grove
              [vendorfriendlyname] => montalto-olive-grove
          )
        [2] => Array(
              [vendorid] => 36
              [vendorname] => Nothin' But A Muffin
              [vendorfriendlyname] => nothin-but-a-muffin
          )
        [3] => Array(
              [vendorid] => 89
              [vendorname] => Organic Family
              [vendorfriendlyname] => organic-family
          )
        [4] => Array(
              [vendorid] => 47
              [vendorname] => pasApas
              [vendorfriendlyname] => pasapas
          )

    )

I have used array_multisort() but it didn't work

Is it possible to sort ?


Solution

  • Try this one : assuming you have array in $rows

    function cmp($a, $b)
    {
        return strcmp($a["vendorname"], $b["vendorname"]);
    }
    
    $array = $rows; 
    usort($array, "cmp");
    
    while (list($key, $value) = each($array)) {
        $new[] =$value ;
    }
    echo "<pre>";
    print_r($new);