Input:
输入:
$sql = array(
array("id"=>"47", "name"=>"Jason", "device"=>"idevice"),
array("id"=>"49", "name"=>"uniKornn", "device"=>"idevice"),
array("id"=>"50", "name"=>"jacob", "device"=>"idevice")
)
Output:
输出:
$sql = array(
array("id"=>"50", "name"=>"jacob", "device"=>"idevice"),
array("id"=>"47", "name"=>"Jason", "device"=>"idevice"),
array("id"=>"49", "name"=>"uniKornn", "device"=>"idevice")
)
I want to set the order of the array $sql, by name, and case-insensitive.
我想按名称和不区分大小写设置数组$sql的顺序。
2 个解决方案
#1
5
function build_sorter($key) {
return function ($a, $b) use ($key) {
return strnatcmp($a[$key], $b[$key]);
};
}
usort($sql, build_sorter('name'));
EDIT: For case-insensitive:
编辑:不区分大小写:
Option 1:
选项1:
function build_sorter($key) {
return function ($a, $b) use ($key) {
return strnatcasecmp($a[$key], $b[$key]);
};
}
usort($sql, build_sorter('name'));
Option 2:
选项2:
function build_sorter($key) {
return function ($a, $b) use ($key) {
return strnatcmp(strtolower($a[$key]), strtolower($b[$key]));
};
}
usort($sql, build_sorter('name'));
Full Code:
完整的代码:
<?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";
}
?>
#2
-1
Or short version for strings
或者是字符串的短版本
function cmp($a, $b)
{
return strcmp($a["name"], $b["name"]);
}
usort($array, "cmp");
#1
5
function build_sorter($key) {
return function ($a, $b) use ($key) {
return strnatcmp($a[$key], $b[$key]);
};
}
usort($sql, build_sorter('name'));
EDIT: For case-insensitive:
编辑:不区分大小写:
Option 1:
选项1:
function build_sorter($key) {
return function ($a, $b) use ($key) {
return strnatcasecmp($a[$key], $b[$key]);
};
}
usort($sql, build_sorter('name'));
Option 2:
选项2:
function build_sorter($key) {
return function ($a, $b) use ($key) {
return strnatcmp(strtolower($a[$key]), strtolower($b[$key]));
};
}
usort($sql, build_sorter('name'));
Full Code:
完整的代码:
<?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";
}
?>
#2
-1
Or short version for strings
或者是字符串的短版本
function cmp($a, $b)
{
return strcmp($a["name"], $b["name"]);
}
usort($array, "cmp");