按名称对数组中的数组进行排序

按名称对数组中的数组进行排序

问题描述:

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.

输入: p>

  $ sql = array(
 
  n array(“id”=>“47”,“name”=>“Jason”,“device”=>“idevice”),
 array(“id”=>“49”,“name”  “=>”uniKornn“,”device“=>”idevice“),
 array(”id“=>”50“,”name“=>”jacob“,”device“=>”  idevice“)
)
  code>  pre> 
 
 

输出: p>

  $ sql = array(
 
 array(
)  “id”=>“50”,“name”=>“jacob”,“device”=>“idevice”),
 array(“id”=>“47”,“name”=>  ;“Jason”,“device”=>“idevice”),
 array(“id”=>“49”,“name”=>“uniKornn”,“device”=>“idevice”)  
)
  code>  pre> 
 
 

我想按名称设置数组$ sql的顺序,不区分大小写。 p> div>

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");