2010-05-18 151 views
1

的價值基礎多維數組我有這樣重新排列的內部陣列

Array 
(
    [0] => Array 
     (
      [cat_name] => Clothing 
      [cat_id] => 1 
      [item_name] => shirt 
      [item_id] => 1 
      [src] => 177 
      [sic] => 78 
     ) 

    [1] => Array 
     (
      [cat_name] => Stationary 
      [cat_id] => 3 
      [item_name] => note book 
      [item_id] => 8 
      [src] => 50 
      [sic] => 10 
     ) 

    [2] => Array 
     (
      [cat_name] => Stationary 
      [cat_id] => 3 
      [item_name] => ball pen 
      [item_id] => 10 
      [src] => 59 
      [sic] => 58 
     ) 

    [3] => Array 
     (
      [cat_name] => Expandable 
      [cat_id] => 4 
      [item_name] => vim powder 
      [item_id] => 14 
      [src] => 34 
      [sic] => 23 
     ) 

    [4] => Array 
     (
      [cat_name] => Clothing 
      [cat_id] => 1 
      [item_name] => pant 
      [item_id] => 16 
      [src] => 100 
      [sic] => 10 
     ) 

) 
現在

數組我想要什麼 首先,它通過CAT_ID排序,然後形成具有以下結構的新陣列

Array 
(
    [0] =>"Clothing"=>Array 
     (

      [0]=>Array 
      (
       [item_name] => shirt 
       [item_id] => 1 
       [src] => 177 
       [sic] => 78 
      ) 
      [1] => Array 
      (
       [item_name] => pant 
       [item_id] => 16 
       [src] => 100 
       [sic] => 10 
      ) 

     ) 
    [1] => "Stationary"=>Array 
     (
     [0] => Array 
      ( 
       [item_name] => note book 
       [item_id] => 8 
       [src] => 50 
       [sic] => 10 
      ) 

     [1] => Array 
      (
       [item_name] => ball pen 
       [item_id] => 10 
       [src] => 59 
       [sic] => 58 
      ) 

     ) 
    [2]=>"Expandable => Array 
     (
     [0] => Array 
      (
       [item_name] => vim powder 
       [item_id] => 14 
       [src] => 34 
       [sic] => 23 
      ) 
     ) 
) 

回答

3

未經測試

$output = array(); 
foreach($array as $item) { 
    if(!isset($output[$item['cat_name']])) { 
     $output[$item['cat_name']] = array(); 
    } 
    $catName = $item['cat_name']; 
    unset($item['cat_name']); 
    $output[$catName][] = $item; 
} 
+0

感謝您的快速回復。有用!但它只輸出每個類別的單個數據(即每個類別的最新項目) 我想要列出所有項目詳細信息的每個類別的多維數組 – diEcho 2010-05-18 10:46:52

+0

@ i-like-php我忘記了最後一行中的方括號。它應該現在工作 – cem 2010-05-18 10:51:00

+0

是的!現在這個工作!兩個答案都很好...感謝Buddy – diEcho 2010-05-18 10:54:41

3
function cmp($a, $b) 
{ 
    if ($a['cat_id'] == $b['cat_id']) { 
     return 0; 
    } 
    return ($a['cat_id'] < $b['cat_id']) ? -1 : 1; 
} 
// sort by cat_id 
usort($array, 'cmp'); 

// create the grouped array 
$res = array(); 
foreach($array as &$item) { 
    $cat_name = $item['cat_name']; 
    unset($item['cat_name'], $item['cat_id']); 
    $res[$cat_name][] = $item; 
} 
+0

太棒了!這是我想要的。 Thaksssss – diEcho 2010-05-18 10:50:57

+0

你的答案也很棒!不要傷心。我會選擇你的回答 – diEcho 2010-05-18 10:56:07

+2

不用擔心,我想我們都是這樣做的,只是爲了好玩。 – nuqqsa 2010-05-18 11:02:34