问题
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!
回答1:
<?php
asort($list);
// OR
array_multisort($list);
?>
PHP Manual: asort() and array_multisort()
回答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
回答3:
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;
回答4:
asort($list);
This will simply do the job for you.
Also see: http://php.net/manual/de/function.asort.php
回答5:
You need to sort using your own comparison function and use it along with usort()
.
来源:https://stackoverflow.com/questions/19391474/alphabetize-array-of-arrays-php