输入:
$sql = array(
array("id"=>"47", "name"=>"Jason", "device"=>"idevice"),
array("id"=>"49", "name"=>"uniKornn", "device"=>"idevice"),
array("id"=>"50", "name"=>"jacob", "device"=>"idevice")
)
输出:
$sql = array(
array("id"=>"50", "name"=>"jacob", "device"=>"idevice"),
array("id"=>"47", "name"=>"Jason", "device"=>"idevice"),
array("id"=>"49", "name"=>"uniKornn", "device"=>"idevice")
)
我想按名称设置数组$ sql的顺序,并且不区分大小写。
答案 0 :(得分:5)
function build_sorter($key) {
return function ($a, $b) use ($key) {
return strnatcmp($a[$key], $b[$key]);
};
}
usort($sql, build_sorter('name'));
编辑:对于不区分大小写:
选项1:
function build_sorter($key) {
return function ($a, $b) use ($key) {
return strnatcasecmp($a[$key], $b[$key]);
};
}
usort($sql, build_sorter('name'));
选项2:
function build_sorter($key) {
return function ($a, $b) use ($key) {
return strnatcmp(strtolower($a[$key]), strtolower($b[$key]));
};
}
usort($sql, build_sorter('name'));
完整代码:
<?php
$sql = array(
array("id"=>"47", "name"=>"Jason", "device"=>"idevice"),
array("id"=>"49", "name"=>"uniKornn", "device"=>"idevice"),
array("id"=>"50", "name"=>"jacob", "device"=>"idevice")
);
function build_sorter($key) {
return function ($a, $b) use ($key) {
return strnatcmp(strtolower($a[$key]), strtolower($b[$key]));
};
}
usort($sql, build_sorter('name'));
foreach ($sql as $item) {
echo $item['id'] . ', ' . $item['name'] .', ' . $item['device'] . "\n";
}
?>
答案 1 :(得分:-1)
或字符串的简短版本
function cmp($a, $b)
{
return strcmp($a["name"], $b["name"]);
}
usort($array, "cmp");