2015-01-12 109 views
-1

我的代碼是:二維數組排序使用PHP

$arr = array(
    array(
     "title" => "Volvo" 
    ), 
    array(
     "title" => "BMW" 
    ), 
    array(
     "title" => "Saab" 
    ), 
    array(
     "title" => "Aam" 
    ) 
); 

$a = aasort($arr,"title"); 

echo "<pre>",print_r($a),"</pre>"; 

function aasort (&$array, $key) { 
    $sorter=array(); 
    $ret=array(); 
    reset($array); 
    foreach ($array as $ii => $va) { 
     $sorter[$ii]=$va[$key]; 
    } 
    natcasesort($sorter); 
    foreach ($sorter as $ii => $va) { 
     $ret[$ii]=$array[$ii]; 
    } 
    $array=$ret; 
    return $array; 
} 

,輸出是:

Array 
(
[3] => Array 
    (
     [title] => Aam 
    ) 

[1] => Array 
    (
     [title] => BMW 
    ) 

[2] => Array 
    (
     [title] => Saab 
    ) 

[0] => Array 
    (
     [title] => Volvo 
    ) 

) 
1 

但我想輸出,如:

Array 
(
[0] => Array 
    (
     [title] => Aam 
    ) 

[1] => Array 
    (
     [title] => BMW 
    ) 

[2] => Array 
    (
     [title] => Saab 
    ) 

[3] => Array 
    (
     [title] => Volvo 
    ) 

) 
1 

怎麼做?

+0

什麼問題呢?任何消除?還是我們想要猜測? – NoLiver92

+0

是的,我正在嘗試做?任何幫助表示讚賞。 –

+0

看看'array_values' – msfoster

回答

0

您可以重新編制一個陣列array_values()

$array = array_values($ret); 
+0

It works .... Thank你非常 –

0

試試這個它會幫助你:

$result = array(); 

    $result = sortArray($array,'key'); 

這裏,$array是排序的數組。所以你可以通過調用sortArray函數對它進行排序。

<?php 

function sortArray($arrData, $p_sort_field, $p_sort_type = false) 
{ 
if(!empty($arrData)) 
{ 
    foreach($arrData as $data) 
    { 
    $newData [] = $data; 
    } 
    for($i=0; $i<count($newData); $i++) 
    { 
    $ar_sort_field[$i]=$newData[$i][$p_sort_field]; 
    } 
    array_multisort($ar_sort_field, ($p_sort_type ? SORT_DESC : SORT_ASC), $newData); 
    return $newData; 
} 
} 

?> 
0

試試這個..

$arr = array(
    array(
    "title" => "Volvo" 
    ), 
    array(
    "title" => "BMW" 
    ), 
    array(
    "title" => "Saab" 
    ), 
    array(
    "title" => "Aam" 
    ) 
    ); 

$arr = msort($arr, array('title')); 

print_r($arr); 

function msort($array, $key, $sort_flags = SORT_REGULAR) { 
    if (is_array($array) && count($array) > 0) { 
     if (!empty($key)) { 
      $mapping = array(); 
      foreach ($array as $k => $v) { 
       $sort_key = ''; 
       if (!is_array($key)) { 
        $sort_key = $v[$key]; 
       } else { 
        // @TODO This should be fixed, now it will be sorted as string 
        foreach ($key as $key_key) { 
         $sort_key .= $v[$key_key]; 
        } 
        $sort_flags = SORT_STRING; 
       } 
       $mapping[$k] = $sort_key; 
      } 
      asort($mapping, $sort_flags); 
      $sorted = array(); 
      foreach ($mapping as $k => $v) { 
       $sorted[] = $array[$k]; 
      } 
      return $sorted; 
     } 
    } 
    return $array; 
} 

結果

Array ([0] => Array ([title] => Aam) [1] => Array ([title] => BMW) 
[2] => Array ([title] => Saab) [3] => Array ([title] => Volvo))`