2011-03-01 3 views
1

중첩 된 PHP 배열을 재귀 적으로 만드는 방법은 무엇입니까?

one,one 
two,two 
sub_one,one 
sub_two,two 
sub_sub_one,sub_one 
sub_sub_two,sub_two 
sub_sub_sub_one,sub_sub_one 
sub_sub_sub_two,sub_sub_two 

이제이 데이터가 들어있는 중첩 배열을 만들고 싶습니다.이 코드는 다음과 같습니다.

<?php 
$lines[] = "one,one"; 
$lines[] = "two,two"; 
$lines[] = "sub_one,one"; 
$lines[] = "sub_two,two"; 
$lines[] = "sub_sub_one,sub_one"; 
$lines[] = "sub_sub_two,sub_two"; 
$lines[] = "sub_sub_sub_one,sub_sub_one"; 
$lines[] = "sub_sub_sub_two,sub_sub_two"; 

foreach($lines as $line) 
{ 
    $tmp = explode(",", $line); 
    $array[$tmp[1]][$tmp[0]] = $tmp[0]; 
} 

foreach($array as $key => $value) 
{ 
    foreach($array[$key] as $value2) 
    { 
     if(array_key_exists($value2, $array) && $value2 != $key) 
     {   
      $array[$key][$value2] = $array[$value2]; 
      $unset[] = $value2; 
     } 
     else 
     { 
      unset($array[$key]); 
     } 
    } 
} 

foreach($unset as $un) 
{ 
    unset($array[$un]); 
} 

print_r($array); 
?> 

그러나이 단계는 3 단계 및 아니오로 진행됩니다. 더. 출력은 다음과 같습니다.

Array 
(
    [one] => Array 
     (
      [sub_one] => Array 
       (
        [sub_sub_one] => sub_sub_one 
       ) 

     ) 

    [two] => Array 
     (
      [sub_two] => Array 
       (
        [sub_sub_two] => sub_sub_two 
       ) 

     ) 

) 

sub_sub_sub_one sub_sub_sub_two가 출력되지 않습니다. 데이터가 얼마나 많은 수준이나 관계가 있더라도 상관없이 반복적으로 코드를 재귀 적으로 만들 수 있습니까?

+0

목록은 항상 (? 부모는 항상 자식들을 전에 표시됩니다) 올바른 순서로됩니다 –

답변

1

Hmm 코드에서 "1"은 최상위 레벨에 있음을 의미하고 "a, b"는 "b"의 하위임을 의미합니다.

모든 링크를 연관 배열 형식으로 변환하면 sub_a가 'a'의 하위 항목 인 경우 $ links [ 'a'] = 'sub_a'와 같이 연결할 수 있습니다. $ nested를 재귀 적으로보다 깊고 깊은 키의 하위로 채 웁니다.

샘플 코드는 다음과 같습니다

<?php 

$nested = array(); 
$links = array(); 

// first, create a structure that contains the connections between elements 
foreach ($lines as $line) { 
    list($child, $parent) = explode(",", $line); 
    if ($child == $parent) { 
    $nested[$parent] = null; 
    } else { 
    // add it to the children of parent 
    $links[$parent][] = $child; 
    } 
} 

function process(&$arr) { 
    global $links; 
    foreach ($arr as $key => $value) { 
    // no more children => stop recursion 
    if (!array_key_exists($key, $links)) { 
     $array[$key] = null; 
     continue; 
    } 
    // insert its children 
    $arr[$key] = array_flip($links[$key]); 
    // recurse down 
    process($arr[$key]); 
    } 
} 

process($nested); 

// $nested contains your m-dim array 
print_r($nested); 

?> 

그리고 출력 :

Array 
(
    [one] => Array 
     (
      [sub_one] => Array 
       (
        [sub_sub_one] => Array 
         (
          [sub_sub_sub_one] => 
         ) 

       ) 

     ) 

    [two] => Array 
     (
      [sub_two] => Array 
       (
        [sub_sub_two] => Array 
         (
          [sub_sub_sub_two] => 
         ) 

       ) 

     ) 

) 
관련 문제