I have an array of strings that I want to sort in order开发者_JAVA百科 of descending length. However, it is a two dimensional array and I'm not sure how to implement a function which will do what I want.
Here is an example of the array:
Array
(
[0] => Array
(
[0] => "abc"
[1] => "def"
[2] => "1234"
)
[1] => Array
(
[0] => "ghijkl"
[1] => "092"
[2] => "234234"
)
[2] => Array
(
[0] => "mn"
[1] => "opq"
[2] => "67843"
)
)
I'm only interested in the length of the first item in the sub-arrays. So ideally it will end up looking like this:
Array
(
[0] => Array
(
[0] => "ghijkl"
[1] => "092"
[2] => "234234"
)
[1] => Array
(
[0] => "abc"
[1] => "def"
[2] => "1234"
)
[2] => Array
(
[0] => "mn"
[1] => "opq"
[2] => "67843"
)
)
Cheers for any help you can give me.
usort($array, function ($a, $b) { return strlen($b[0]) - strlen($a[0]); });
(uses PHP 5.3 syntax)
<?php
$your_array = array
(
array
(
"abc",
"def",
"1234"
),
array
(
"ghijkl",
"092",
"234234"
),
array
(
"mn",
"opq",
"67843"
)
);
function customSort(Array $a, Array $b){
return strlen($b[0]) - strlen($a[0]);
}
usort($your_array, 'customSort');
var_dump($your_array);
精彩评论