"PHP 트리 자료를 depth 테이블로 변환"의 두 판 사이의 차이

(새 문서: ==개요== ;PHP 트리 자료를 depth 테이블로 변환 <source lang='php' run> $tree = [ [ 'id' => 1, 'value' => '/', 'children' => [ [ 'id' => 2, 'value' => 'bin' ], [...)
 
잔글 (봇: 자동으로 텍스트 교체 (-</source> +</syntaxhighlight>, -<source +<syntaxhighlight ))
 
2번째 줄: 2번째 줄:
;PHP 트리 자료를 depth 테이블로 변환
;PHP 트리 자료를 depth 테이블로 변환


<source lang='php' run>
<syntaxhighlight lang='php' run>
$tree = [
$tree = [
   [ 'id' => 1, 'value' => '/', 'children' => [
   [ 'id' => 1, 'value' => '/', 'children' => [
34번째 줄: 34번째 줄:
   echo "id: ${row['id']}, parent_id:${row['parent_id']}, value:${row['value']}\n";
   echo "id: ${row['id']}, parent_id:${row['parent_id']}, value:${row['value']}\n";
}
}
</source>
</syntaxhighlight>


==같이 보기==
==같이 보기==

2020년 11월 2일 (월) 02:57 기준 최신판

1 개요[ | ]

PHP 트리 자료를 depth 테이블로 변환
$tree = [
  [ 'id' => 1, 'value' => '/', 'children' => [
    [ 'id' => 2, 'value' => 'bin' ],
    [ 'id' => 3, 'value' => 'etc' ],
    [ 'id' => 4, 'value' => 'usr', 'children' => [
      [ 'id' => 5, 'value' => 'bin' ],
    ]],
    [ 'id' => 6, 'value' => 'var', 'children' => [
      [ 'id' => 7, 'value' => 'log' ],
    ]]
  ]]
];

function tree2parent_table($arr, $parent_id=0) {
  $res = [];
  foreach($arr as $item) {
    if(isset($item['children'])) {
      $res = array_merge($res, tree2parent_table($item['children'], $item['id']));
      unset($item['children']);
    }
    $item['parent_id'] = $parent_id;
    $res[] = $item;  
  }
  if( $parent_id == 0 ) sort($res);
  return $res;
}

$table = tree2parent_table($tree);
foreach($table as $row) {
  echo "id: ${row['id']}, parent_id:${row['parent_id']}, value:${row['value']}\n";
}

2 같이 보기[ | ]

문서 댓글 ({{ doc_comments.length }})
{{ comment.name }} {{ comment.created | snstime }}