-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!

2

5 Answers 5

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

Sign up to request clarification or add additional context in comments.

2 Comments

Or: function reindex($a,$b){ return strcmp($a[0],$b[0]);} (which does the same thing).
1
<?php

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

?>

PHP Manual: asort() and array_multisort()

Comments

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;

Comments

1
asort($list);

This will simply do the job for you.

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

Comments

-1

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.