Confusing array sorting in PHP
What's the best way to sort this array alphabetically, by String1? The key numbering should always be numerical still.
Before:
Key | String1 Int1 String2 Int2
--------------------------------------
0 | Alligator 3 Cake 7
1 | Crocodile 17 foobar 9
2 | Bear 1 test 6
3 | Aardvark 2 lolwhat 3
After:
Key | String1 Int1 String2 Int2
--------------------------------------
0 | Aardvark 2 lolwhat 3
1 | Alligator 3 Cake 7
2 | Bear 1 test 6
3 | Crocodile 17 foobar开发者_如何学编程 9
Essentially, I have an array which has a bunch of arrays in it, how can I sort those arrays within the first array alphabetically using a particular element?
You probably want usort
which lets you define a comparator callback function.
http://www.php.net/manual/en/function.usort.php
You will want a compare function like the following:
function compare($a, $b)
{
if ($a['String1'] < $b['String1'])
return -1;
if ($a['String1'] > $b['String1'])
return 1;
// At this point the strings are identical and you can go into
// a second value to compare something else if you wish
if ($a['String2'] < $b['String2'])
return -1;
if ($a['String2'] > $b['String2'])
return 1;
// as long as you cover the three situations you are fine.
return 0
}
function str1cmp($a, $b) {
return strcmp($a['string1'], $b['string1']);
}
usort($array, 'str1cmp');
精彩评论