Reputation:
Good day.
We have array:
array(3) {
[1]=>
array(9) {
[1]=>
string(12) "aaandroid.ru"
[2]=>
string(1) "0"
[3]=>
string(1) "0"
[4]=>
string(1) "0"
[5]=>
string(1) "0"
[6]=>
string(1) "0"
[7]=>
string(5) "Test2"
[8]=>
string(10) "2012-03-27"
[9]=>
string(10) "2013-04-29"
}
[2]=>
array(9) {
[1]=>
string(7) "aaga.ru"
[2]=>
string(1) "0"
[3]=>
string(1) "0"
[4]=>
string(1) "0"
[5]=>
string(1) "0"
[6]=>
string(1) "0"
[7]=>
string(8) "Test1"
[8]=>
string(10) "2008-02-21"
[9]=>
string(10) "2013-04-29"
}
[3]=>
array(9) {
[1]=>
string(10) "aatrakc.ru"
[2]=>
string(1) "0"
[3]=>
string(1) "0"
[4]=>
string(1) "0"
[5]=>
string(1) "0"
[6]=>
string(1) "0"
[7]=>
string(8) "Test3"
[8]=>
string(10) "2012-03-27"
[9]=>
string(10) "2013-04-29"
}
Tell me please how sort data in array with key?
For example i would like get array where data sorting on element 7, ie. in result i would like get array:
array(3) {
[1]=>
array(9) {
[1]=>
string(7) "aaga.ru"
[2]=>
string(1) "0"
[3]=>
string(1) "0"
[4]=>
string(1) "0"
[5]=>
string(1) "0"
[6]=>
string(1) "0"
[7]=>
string(8) "Test1"
[8]=>
string(10) "2008-02-21"
[9]=>
string(10) "2013-04-29"
}
[1]=>
string(12) "aaandroid.ru"
[2]=>
string(1) "0"
[3]=>
string(1) "0"
[4]=>
string(1) "0"
[5]=>
string(1) "0"
[6]=>
string(1) "0"
[7]=>
string(5) "Test2"
[8]=>
string(10) "2012-03-27"
[9]=>
string(10) "2013-04-29"
}
[3]=>
array(9) {
[1]=>
string(10) "aatrakc.ru"
[2]=>
string(1) "0"
[3]=>
string(1) "0"
[4]=>
string(1) "0"
[5]=>
string(1) "0"
[6]=>
string(1) "0"
[7]=>
string(8) "Test3"
[8]=>
string(10) "2012-03-27"
[9]=>
string(10) "2013-04-29"
}
Tell me please it really an how make it?
Upvotes: 0
Views: 47
Reputation: 1
Continuing Hidde's answer, if you want to reverse the order of the sort you would still use usort()
, but you reverse the order of the parameters in the call to strcmp()
. This will reverse which of the two arrays usort()
sees as the larger value.
usort($myArray, function ($a, $b) {
return strcmp($b[7], $a[7]);
});
This uses an anonymous function, so it will only work on Php 5.3 or later. If you have to work on 5.2 define a function to use as the callback.
function mySortFunction($a, $b) {
return strcmp($b[7], $a[7]);
}
usort($myArray, 'mySortFunction');
See:
Upvotes: 0
Reputation: 11911
Check the PHP usort
function: http://www.php.net/manual/en/function.usort.php.
It provides (in place) sorting based on a callback, which you can create.
Example:
usort($myArray, function ($a, $b) {
return strcmp($a[7], $b[7]);
});
Upvotes: 2