Array sort by value number chars
Hi thinking i have an array like this :
[0]=>[
[0]=>'Hey',
[1]=>'H',
[2]=>'He',
]
now i would like to sort by number chars and return somenthing like this:
[0]=>[
[0]=>'H',
[1]=>'He',
[2]=>'Hey',
]
maybe the answer is array_sort() but i'm not able to do that. also i would not like to loop the array to check the number chars of values, but if it's the only way i need to use anyway :P
BTW
how to return this same array ordered by ['name'] key number of chars ASC (h - he -hey -heyh - heyhey )?
array(5) {
[0]=>
array(2) {
["id"]=>
object(MongoId)#26 (1) {
["$id"]=>
string(24) "4e72858ccaa47ca608030000"
}
["name"]=>
string(4) "h"
}
[1]=>
array(2) {
["id"]=>
开发者_Go百科 object(MongoId)#29 (1) {
["$id"]=>
string(24) "4e72858ccaa47ca608040000"
}
["name"]=>
string(10) "hey"
}
[2]=>
array(2) {
["id"]=>
object(MongoId)#31 (1) {
["$id"]=>
string(24) "4e72858ccaa47ca608400000"
}
["name"]=>
string(1) "heyhey"
}
[3]=>
array(2) {
["id"]=>
object(MongoId)#33 (1) {
["$id"]=>
string(24) "4e72858ccaa47ca6081a0000"
}
["name"]=>
string(6) "he"
}
[4]=>
array(2) {
["id"]=>
object(MongoId)#35 (1) {
["$id"]=>
string(24) "4e72858ccaa47ca6083d0000"
}
["name"]=>
string(3) "heyh"
}
}
If you want to sort by the number of characters, usort
is the way to go. It lets you define your own sorting function.
function lengthsort($s1, $s2) {
if (strlen($s1['name']) < strlen($s2['name'])) {
return -1;
} elseif (strlen($s1['name']) > strlen($s2['name'])) {
return 1;
} else {
return 0;
}
}
usort($array, 'lengthsort');
PHP's usort
allows you to specify a custom sorting function:
<?php
$arr = array(array('Hey', 'H', 'He'));
print_r($arr);
usort($arr[0], function($a, $b) {
return strlen($a) - strlen($b);
});
print_r($arr);
?>
DEMO
their is no function like array_sort() in php you need to use only sort() function which sorts the array by the values and keep the key information as it is.
$arr = array('0'=>array('0'=>'Hey','1'=>'H','2'=>'He'));
foreach($arr as $k=>$v):
$arr1 = $v;
sort($arr1);
print_r($arr1);
endforeach;
?>
take a look at usort() wich lets you define an own function for sorting:
$myarray = array('Hey','H','He');
usort($myarray,function($a, $b){
if (strlen($a) == strlen($b)) {
return 0;
}
return (strlen($a) < strlen($b)) ? -1 : 1;
});
var_dump($myarray); // array('H','He','Hey')
note that i'm using an inline-function here, wich is possible with php 5.3+ - in lower versions of php you'll have to define a traditional function and pass the name of that function to usort()
精彩评论