在这种情况下,我需要按给定键0
的值对数组进行排序。
所以这是我的数组:
array(11) {
[0]=> array(3) {
[0]=> string(3) "5"
[1]=> string(1) "3"
[2]=> string(2) "21"
}
[1]=> array(3) {
[0]=> string(3) "0.5"
[1]=> string(1) "3"
[2]=> string(3) "may"
}
[2]=> array(3) {
[0]=> string(3) "2.2"
[1]=> string(1) "3"
[2]=> string(16) "sport"
}
}
结果必须按键0
:
array(11) {
[0]=> array(3) {
[0]=> string(3) "0.5"
[1]=> string(1) "3"
[2]=> string(2) "may"
}
[1]=> array(3) {
[0]=> string(3) "2.2"
[1]=> string(1) "3"
[2]=> string(3) "sport"
}
[2]=> array(3) {
[0]=> string(3) "5"
[1]=> string(1) "3"
[2]=> string(16) "21"
}
}
我尝试使用此代码:
function sort_by_second($i,$j){return $i[0]-$j[0];};
usort($mas,'sort_by_second');
我不明白为什么它不起作用。
答案 0 :(得分:0)
请尝试以下代码:
$array = array(
array("5","3","21"),
array("0.5","3","may"),
array("2.2","3","sport"),
);
//print_r($array);
function subval_sort($a,$subkey) {
foreach($a as $k=>$v) {
$b[$k] = strtolower($v[$subkey]);
}
asort($b);
foreach($b as $key=>$val) {
$c[] = $a[$key];
}
return $c;
}
$result = subval_sort($array, 0);
print_r($result);
的结果:强>
Array
(
[0] => Array
(
[0] => 0.5
[1] => 3
[2] => may
)
[1] => Array
(
[0] => 2.2
[1] => 3
[2] => sport
)
[2] => Array
(
[0] => 5
[1] => 3
[2] => 21
)
)
的演示:强>
答案 1 :(得分:0)
PHP> = 5.5.0:
array_multisort(array_column($array, 0), SORT_ASC, $array);