我有一个如下所示的数组:
Array ( [0] => Array ( [id] => 1103 [age] => 37 [gen] => C:3:2:5:1:4 ) [1] => Array ( [id] => 1104 [age] => 37 [gen] => A:3:1:4:1 ) [2] => Array ( [id] => 1105 [age] => 36 [gen] => A:3:2:3:2 ) [3] => Array ( [id] => 1106 [age] => 32 [gen] => B:2:5:1:2:2 ) [4] => Array ( [id] => 1107 [age] => 31 [gen] => C:3:4:4:5:3 [5] => Array ( [id] => 1104 [age] => 37 [gen] => A:3:1:4:1:6 ))
我想按gen键对数组进行排序,结果如下:
A:3:1:4:1:6
A:3:2:3:2
B:2:5:1:2:2
C:3:2:5:1:4
C:3:4:4:5:3
我试过这段代码:
uasort($newArray, function($a, $b) {
return strnatcasecmp($a['ngen'], $b['ngen']);
});
但无法得到正确的结果。有什么想法吗?
答案 0 :(得分:0)
<?php
$ar = [
["id" => 1103, "age" => 37, "gen" => "C:3:2:5:1:4"],
["id" => 1104, "age" => 37, "gen" => "A:3:1:4:1"],
["id" => 1105, "age" => 36, "gen" => "A:3:2:3:2"],
["id" => 1106, "age" => 32, "gen" => "B:2:5:1:2:2"],
["id" => 1107, "age" => 31, "gen" => "C:3:4:4:5:3"],
["id" => 1108, "age" => 37, "gen" => "A:3:1:4:1:6"],
];
usort($ar, function ($a, $b) {
return strcmp($a['gen'], $b['gen']);
});
foreach($ar as $r)
echo($r['id'] . " " . $r['gen'] . PHP_EOL);
会给你:
1104 A:3:1:4:1
1108 A:3:1:4:1:6
1105 A:3:2:3:2
1106 B:2:5:1:2:2
1103 C:3:2:5:1:4
1107 C:3:4:4:5:3
答案 1 :(得分:0)
此函数将帮助您对数组进行排序,只需传递要对数组进行排序的键。
function build_sorter($key)
{
return function ($a, $b) use ($key) {
return strnatcmp($a[$key], $b[$key]);
};
}
示例代码:
$results = array(0 => array ( 'id' => 1103, 'age' => 37, 'gen' => 'C:3:2:5:1:4' ),
1 => array ( 'id' => 1104, 'age' => 37, 'gen' => 'A:3:1:4:1' ),
2 => array ( 'id' => 1105, 'age' => 36, 'gen' => 'A:3:2:3:2' ),
3 => array ( 'id' => 1106, 'age' => 32, 'gen' => 'B:2:5:1:2:2' ),
4 => array ( 'id' => 1107, 'age' => 31, 'gen' => 'C:3:4:4:5:3' ),
5 => array ( 'id' => 1104, 'age' => 37, 'gen' => 'A:3:1:4:1:6' )
);
usort($results, build_sorter('gen'));
echo "<pre>"; print_r($results) ;
只需在回拨中调用build_sorter('gen')
并传递密钥gen
这会让你:
Array
(
[0] => Array
(
[id] => 1104
[age] => 37
[gen] => A:3:1:4:1
)
[1] => Array
(
[id] => 1104
[age] => 37
[gen] => A:3:1:4:1:6
)
[2] => Array
(
[id] => 1105
[age] => 36
[gen] => A:3:2:3:2
)
[3] => Array
(
[id] => 1106
[age] => 32
[gen] => B:2:5:1:2:2
)
[4] => Array
(
[id] => 1103
[age] => 37
[gen] => C:3:2:5:1:4
)
[5] => Array
(
[id] => 1107
[age] => 31
[gen] => C:3:4:4:5:3
)
)