2013-08-19 60 views
1

我有一個數組如下排序..PHP多維數組與不區分大小寫

Array 
(
    [0] => Array 
     (
      [0] => Array 
       (
        [name] => Henry 
       ) 
     ) 
    [1] => Array 
     (
      [0] => Array 
       (
        [name] => jack 
       ) 
     ) 
    [2] => Array 
     (
      [0] => Array 
       (
        [name] => Albert 
       ) 
     ) 
    [3] => Array 
     (
      [0] => Array 
       (
        [name] => bunny 
       ) 
     ) 

我需要排序此陣列由名字在不區分大小寫的ASC &遞減順序。請幫助我..

+0

+1有趣的問題,amdavadi :) – SagarPPanchal

回答

2

我寫了一個PHP函數幾年前這樣做的事情。

function subval_sort($a, $subkey, $reverse = false) 
{ 
    if (!$a) 
    { 
     return array(); 
    } 

    $b = array(); 

    foreach ($a as $k => $v) 
    { 
     $b[$k] = strtolower($v[$subkey]); 
    } 

    if ($reverse) 
    { 
     arsort($b); 
    } 
    else 
    { 
     asort($b); 
    } 

    $c = array(); 

    foreach ($b as $key => $val) 
    { 
     $c[] = $a[$key]; 
    } 

    return $c; 
} 

使用它像subval_sort($array, 'name')

0

排序功能:

使用我的自定義功能來實現您的解決方案,它正在

function multisort (&$array, $key) { 
$valsort=array(); 
$ret=array(); 
reset($array); 
foreach ($array as $ii => $va) { 
    $valsort[$ii]=$va[$key]; 
} 
asort($valsort); 
foreach ($valsort as $ii => $va) { 
    $ret[$ii]=$array[$ii]; 
} 
$array=$ret; 
} 

multisort($multiarr,"order"); 

希望這將肯定幫你。

0
$array = array(
    array('Henry'), 
    array('Michael'), 
    array('Steve'), 
    array('Daniel'), 
    array('Albert'), 
); 


// Comparison function 
function cmp($a, $b) { 
    if ($a[0] == $b[0]) { 
     return 0; 
    } 
    return ($a[0] < $b[0]) ? -1 : 1; 
} 

// Array to be sorted 
print_r($array); 

// Sort and print the resulting array 
uasort($array, 'cmp'); 
print_r($array); 

輸出:

Array 
(
    [0] => Array 
     (
      [0] => Henry 
     ) 

    [1] => Array 
     (
      [0] => Michael 
     ) 

    [2] => Array 
     (
      [0] => Steve 
     ) 

    [3] => Array 
     (
      [0] => Daniel 
     ) 

    [4] => Array 
     (
      [0] => Albert 
     ) 

) 
Array 
(
    [4] => Array 
     (
      [0] => Albert 
     ) 

    [3] => Array 
     (
      [0] => Daniel 
     ) 

    [0] => Array 
     (
      [0] => Henry 
     ) 

    [1] => Array 
     (
      [0] => Michael 
     ) 

    [2] => Array 
     (
      [0] => Steve 
     ) 

)