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.
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:
function build_sorter($key) {
return function ($a, $b) use ($key) {
return strnatcasecmp($a[$key], $b[$key]);
};
}
usort($sql, build_sorter('name'));
Option 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'] . "
";
}
?>
Or short version for strings
function cmp($a, $b)
{
return strcmp($a["name"], $b["name"]);
}
usort($array, "cmp");