使用 array_multisort 對多維數組排序


array_multisort() 函數對多個數組或多維數組進行排序。php

用法詳看:http://www.w3school.com.cn/php/func_array_multisort.asp數組


例子:ide

把二維數組按name長度賦值給id,並從新排序。函數

$arr = array(
    array('id' => 0, 'name' => '123833'),
    array('id' => 0, 'name' => 'aaa'),
    array('id' => 0, 'name' => 'albabaababa'),
    array('id' => 0, 'name' => '12356'),
    array('id' => 0, 'name' => '123abc')
);
foreach($arr as $k=>&$v){    //此處引用賦值纔會改變原數組的值
    $v['id'] = strlen($v['name']);  
}
array_multisort($arr);   //對多維數組排序
echo "<pre>";
print_r($arr);
echo "</pre>";

此時數組變爲:code

Array
(
    [0] => Array
        (
            [id] => 3
            [name] => aaa
        )
    [1] => Array
        (
            [id] => 5
            [name] => 12356
        )
    [2] => Array
        (
            [id] => 6
            [name] => 123833
        )
    [3] => Array
        (
            [id] => 6
            [name] => 123abc
        )
    [4] => Array
        (
            [id] => 11
            [name] => albabaababa
        )
)
相關文章
相關標籤/搜索