-1

I have an array of arrays formatted like the following:

$list = [ ["fdsa","1","fdsa"],["sadf","0","asdf"],["frfrf","0","sadfdsf"] ]

How can I alphabetize $list based on the first value of every inner array?

Thanks!

Sammitch
  • 25,490
  • 6
  • 42
  • 70
nshah
  • 587
  • 2
  • 9
  • 30

5 Answers5

2

I had this function for another answer but it can be modded to do the same:

// This sorts simply by alphabetic order
function reindex( $a, $b )
{
    // Here we grab the values of the 'code' keys from within the array.
    $val1 = $a[0];
    $val2 = $b[0];

    // Compare string alphabetically
    if( $val1 > $val2 ) {
        return 1;
    } elseif( $val1 < $val2 ) {
        return -1;
    } else {
        return 0;
    }
}

// Call it like this:
usort( $array, 'reindex' );

print_r( $array );

Original: Sorting multidimensional array based on the order of plain array

Community
  • 1
  • 1
Jason
  • 1,967
  • 1
  • 13
  • 16
1
<?php

asort($list);
// OR
array_multisort($list);

?>

PHP Manual: asort() and array_multisort()

Fleshgrinder
  • 14,476
  • 4
  • 41
  • 51
1
function order($a, $b){
     if ($a[0] == $b[0]) {
            return 0;
        }
        return ($a[0] < $b[0]) ? -1 : 1;
    }

$list = [ ["fdsa","1","fdsa"],["sadf","0","asdf"],["frfrf","0","sadfdsf"] ];

    usort($list, "order");


    var_dump($list); die;
Felix
  • 351
  • 1
  • 9
1
asort($list);

This will simply do the job for you.

Also see: http://php.net/manual/de/function.asort.php

sebbo
  • 2,783
  • 1
  • 17
  • 37
-1

You need to sort using your own comparison function and use it along with usort().

Jay Nebhwani
  • 856
  • 6
  • 11