2010-11-18 66 views
0

如何重新排列如下數組PHP重新排序數組以反映父/ ID層次

[0] => Array 
    (
     [id] => 1 
     [parent_id] => 0 
     [name] => Accueil 
    ) 

[1] => Array 
    (
     [id] => 2 
     [parent_id] => 0 
     [name] => Exposants 
    ) 

[2] => Array 
    (
     [id] => 3 
     [parent_id] => 0 
     [name] => Visiteurs 
    ) 

[3] => Array 
    (
     [id] => 4 
     [parent_id] => 0 
     [name] => Medias 
    ) 

[4] => Array 
    (
     [id] => 5 
     [parent_id] => 0 
     [name] => Activités 
    ) 

[5] => Array 
    (
     [id] => 6 
     [parent_id] => 1 
     [name] => Contact 
    ) 

[6] => Array 
    (
     [id] => 7 
     [parent_id] => 3 
     [name] => Partenaires 
    ) 

[7] => Array 
    (
     [id] => 8 
     [parent_id] => 2 
     [name] => News 
    ) 

於是我想出了一個反映層次結構如圖中的ID和PARENT_ID領域的陣列?數組鍵是數組元素的ID字段是父項。在這個數組裏面每次都是一個以ID字段爲關鍵字的子數組。示例:

[1] => Array 
     (
      [name] => Accueil 
      [children] => array(
       [0] => bla, 
       [3]  => bla2 
      ) 
     ) 

    [2] => Array 
     (
      [name] => Something 
      [children] => array(
       [4] => bla3, 
      ) 
     ) 
+0

如果你在主數組中有所有的「人員」,將這些ID單獨存儲在「子」鍵下而不是將其作爲鍵/值存儲是不明智的(假設該值是名稱或某些)? – Orbling 2010-11-18 16:12:29

回答

0

您可以使這更幹,但它是一種快速和骯髒的方式來處理它。此外,如果可以保證每個子記錄具有有效的父記錄,並且有效的父記錄在原始數組中的子記錄之前,則可以刪除6行。

$sorted = array(); 
foreach($orig_ary as $item) { 
    if ($item['parent_id'] === 0) { 
    if (!array_key_exists($item['id'], $sorted)) { 
     $sorted[ $item['id'] ] = array(
     'name' => '', 
     'children' => array() 
    ); 
    } 
    $sorted[ $item['id'] ]['name'] = $item['name']; 
    } else { 
    if (!array_key_exists($item['parent_id'], $sorted)) { 
     $sorted[ $item['parent_id'] ] = array(
     'name' => '', 
     'children' => array() 
    ); 
    } 
    $sorted[ $item['parent_id'] ]['children'][ $item['id'] ] = $item['name']; 
    } 
} 
2

適用於任何深度,讓孩子先於父母:

<?php 
$p = array(0 => array()); 
foreach($nodes as $n) 
{ 
    $pid = $n['parent_id']; 
    $id = $n['id']; 

    if (!isset($p[$pid])) 
    $p[$pid] = array('child' => array()); 

    if (isset($p[$id])) 
    $child = &$p[$id]['child']; 
    else 
    $child = array(); 

    $p[$id] = $n; 
    $p[$id]['child'] = &$child; 
    unset($p[$id]['parent_id']); 
    unset($child); 

    $p[$pid]['child'][] = &$p[$id];  
} 
$nodes = $p['0']['child']; 
unset($p); 
?> 

$nodes結果使用var_dump看結構。它接近你的建議。主要區別在於鍵不是ID。