2014-01-26 211 views
2

輸入:排序陣列,按名稱

$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的順序,按名稱,和不區分大小寫的。

+1

你試過什麼? – Crozin

+0

我已經嘗試過使用'sort($ sql)',但那不起作用... – 131

+0

ksort($ sql) –

回答

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

?> 
+0

這個工作方式,但區分大小寫。它由A-Z a-z命令。我希望它不區分大小寫 – 131

+0

['strnatcasecmp'](http://www.php.net/manual/en/function.strnatcasecmp.php) – Emissary

+0

這樣做。謝謝! – 131

-1

或短版本的字符串

function cmp($a, $b) 
{ 
    return strcmp($a["name"], $b["name"]); 
} 

usort($array, "cmp");