PHP depth 테이블을 트리 자료로 변환

1 개요[ | ]

PHP depth 테이블을 트리 자료로 변환
<?php
$table1 = [
  ['id'=>1, 'value'=>'/'  , 'depth'=>0],
  ['id'=>2, 'value'=>'bin', 'depth'=>1],
  ['id'=>3, 'value'=>'etc', 'depth'=>1],
  ['id'=>4, 'value'=>'usr', 'depth'=>1],
  ['id'=>5, 'value'=>'bin', 'depth'=>2],
  ['id'=>6, 'value'=>'var', 'depth'=>1],
  ['id'=>7, 'value'=>'log', 'depth'=>2],
];

function depth_table2parent_table($rows) {
  $res = [];
  $temp_parent_ids = [];
  foreach($rows as $row) {
    $id = $row['id'];
    $depth = $row['depth'];
    $row['parent_id'] = $temp_parent_ids[$depth-1] ?? 0;
    $temp_parent_ids[$depth] = $id;
    unset($row['depth']); // remove depth (optional)
    $res[] = $row;
  }
  return $res;
}

function buildTree($rows, $parent_id=0) {
  $res = [];
  foreach($rows as $row) {
    if($row['parent_id'] == $parent_id) {
      $children = buildTree($rows, $row['id']);
      if($children) $row['children'] = $children;
      unset($row['parent_id']); // remove parent_id (optional)
      $res[$row['id']] = $row;
    }
  }
  return $res;
}

$tree = buildTree(depth_table2parent_table($table1));
print_r($tree);

2 같이 보기[ | ]

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