2012-12-07 5 views
1

나는 이것을 며칠 동안 찾고 있었지만 캔트는 안주를 찾는 것처럼 보인다. 나는배열에 계층 적 데이터

$startArray = Array(array('name' => 'A', 'hierarchy' => '1'), 
    array('name' => 'B', 'hierarchy' => '1.2'), 
    array('name' => 'C', 'hierarchy' => '1.3'), 
    array('name' => 'D', 'hierarchy' => '1.3.1') 
); 

와 내가 좋아하는 것 같은 배열

$endResult = 
    array(
      array('name' => 'A', 
      'children' => array(
       array('name'=> 'b'), 
       array('name'=> 'c', 
       'children' => array('name' => 'D') 
       ) 
      ) 
    ); 

모든 제안에 가야? 감사합니다.

+0

첫 번째 배열을 두 번째 배열로 변환 하시겠습니까? 당신이 원하는 것을 구체적으로 작성하십시오. – SubRed

+1

''name '=>'b ','name '=>'c''는''name '=>'c'' 만 결과로 "예상 결과"가 부정확합니다. array ('name'=> 'b'), array ('name'=> 'c', 'children'=> array (...))' – Passerby

+0

당신 말이 맞아요, 나는 분명히 그것을 빨리 적어 두었습니다. 나는 질문을 개선했다, 나는 그것이 지금 이해할 수 있기를 바란다? 미리 감사드립니다! –

답변

2

여기 긴 해결책이 있습니다. 아마도 여기에 함수를 넣을 수 있습니다. 이 파일을 복사하여 빈 문서 안에 붙여넣고 브라우저에서 결과를 확인하십시오.

<pre> 
<?php 

    $orig = array(
     array('name' => 'A', 'hierarchy' => '1'), 
     array('name' => 'B', 'hierarchy' => '1.2'), 
     array('name' => 'C', 'hierarchy' => '1.3'), 
     array('name' => 'D', 'hierarchy' => '1.3.1') 
     //,array('name' => 'E', 'hierarchy' => '1.2.1') 
     //,array('name' => 'F', 'hierarchy' => '2.1') 
    ); 

    function special_sort($arr1,$arr2) { 
     $h1 = $arr1['hierarchy']; 
     $h2 = $arr2['hierarchy']; 
     $ch1 = count($h1); 
     $ch2 = count($h2); 
     if ($ch1 < $ch2) return -1; 
     if ($ch1 > $ch2) return 1; 
     return $h1 > $h2 ? 1 : ($h1 < $h2 ? -1 : 0); 
    } 
    // this first checks lengths and then values 
    // so 1.3 gets -1 against 1.2.1 whereas 
    // 1.3.2 still gets 1 against 1.3.1 

    $temp = $orig; 
    // temporary array to keep your original untouched 
    foreach ($temp as &$arr) { 
     $arr['hierarchy'] = explode('.',$arr['hierarchy']); 
     // turn hierachy numbers into arrays for later 
     // sorting purposes 
    } 
    unset($arr); 
    // get rid of the reference used in the loop 
    usort($temp,'special_sort'); 
    // sort by the sort function above 

    echo '<h2>$orig</h2>'; print_r($orig); 
    echo '<h2>$temp</h2>'; print_r($temp); 
    // for you to see what it looks like now 

    $res = array(); 
    // our final array 

    // by the following loop we're using the hierarcy 
    // numbers as keys to push into the result array 
    foreach ($temp as $arr) { 
     $h = $arr['hierarchy']; 
     if (count($h) == 1) { 
     // this is for those with single hierarchy 
     // numbers such as 1, 2, etc. 
      $res[$h[0]] = array('name'=>$arr['name']); 
      continue; 
     } 
     if (!isset($res[$h[0]])) 
      $res[$h[0]] = array('name'=>''); 
     // if, say this is 2.1 but there is no 2 in the array then 
     // we need to create that. see the last commented item in 
     // the original array. uncomment it to see why I wrote this 
     $newLoc =& $res[$h[0]]; 
     // reference of the new place in result 
     // array to push the item 
     for ($i = 1; $i < count($h); $i++) { 
      if (!isset($newLoc['children'])) 
       $newLoc['children'] = array(); 
      // create children array if it doesn't exist 
      if (!isset($newLoc['children'][$h[$i]])) 
       $newLoc['children'][$h[$i]] = array(); 
      // create children[hierarch key] array if it doesn't exist 
      $newLoc =& $newLoc['children'][$h[$i]]; 
      // update reference 
     } 
     $newLoc = array('name'=>$arr['name']); 
     // assign the new name to this reference 
     unset($newLoc); 
     // get rid of the reference 
    } 

    unset($temp); 
    // get rid of the array now that we're done with it 

    echo '<h2>$res</h2>'; print_r($res); 

    function fix_keys($array) { 
     foreach ($array as $k => $val) { 
      if (is_array($val)) $array[$k] = fix_keys($val); 
     } 
     if(is_numeric($k)) return array_values($array); 
     return $array; 
    } 
    // function courtesy of Lobos, 
    // http://stackoverflow.com/a/12399408/913097 

    $endRes = fix_keys($res); 
    // create the end result array. this is actually 
    // a copy of the $res array except the numeric 
    // keys were reset. 

    unset($res); 
    // get rid of the last unused array 

    echo '<h2>$endRes</h2>'; print_r($endRes); 

?> 
</pre> 
+0

와우 그 매력처럼 작동합니다. 고마워요! –

+0

@ SimonNouwens가 도와 주니 기뻤습니다. – inhan

0

올바른 배열이 없으면 값이 다시 작성됩니다. 대략 다음과 같아야합니다.

$arr = array(
    array('name' => 'a', 'hierarchy' => '1'), 
    array('name' => 'b', 'hierarchy' => '1.2'), 
); 
+0

귀하의 권리, 잘못 입력 된, 감사합니다 –