使用できますusort
$names = Array(
"0" => Array("name" => "B","prename" => "A"),
"1" => Array("name" => "D","prename" => "B"),
"2" => Array("name" => "A","prename" => "C"),
"3" => Array("name" => "B","prename" => "D")
);
例1
__xsort($names,"name");
var_dump($names);
出力
array
0 =>
array
'name' => string 'A' (length=1)
'prename' => string 'C' (length=1)
1 =>
array
'name' => string 'B' (length=1)
'prename' => string 'A' (length=1)
2 =>
array
'name' => string 'B' (length=1)
'prename' => string 'D' (length=1)
3 =>
array
'name' => string 'D' (length=1)
'prename' => string 'B' (length=1)
例2
__xsort($names,"prename");
var_dump($names);
出力
array
0 =>
array
'name' => string 'B' (length=1)
'prename' => string 'A' (length=1)
1 =>
array
'name' => string 'D' (length=1)
'prename' => string 'B' (length=1)
2 =>
array
'name' => string 'A' (length=1)
'prename' => string 'C' (length=1)
3 =>
array
'name' => string 'B' (length=1)
'prename' => string 'D' (length=1))
使用した機能
function __xsort(&$names,$key) {
usort($names, function ($a, $b) use($key) {
if ($a[$key] == $b[$key]) {
return 0;
}
return ($a[$key] < $b[$key]) ? - 1 : 1;
});
return $names;
}