Domanda

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!

È stato utile?

Soluzione 2

<?php

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

?>

PHP Manual: asort() and array_multisort()

Altri suggerimenti

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

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;
asort($list);

This will simply do the job for you.

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

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

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top