PHP 트리 자료를 parent_id 테이블로 변환

Jmnote (토론 | 기여)님의 2020년 5월 26일 (화) 00:24 판 (새 문서: ==개요== {{DISPLAYTITLE:PHP 트리 자료를 parent_id 테이블로 변환}} ;PHP 트리 자료를 parent id 테이블로 변환 <source lang='php' run> $tree = [ [ 'id' => 1, 'v...)
(차이) ← 이전 판 | 최신판 (차이) | 다음 판 → (차이)

1 개요

PHP 트리 자료를 parent id 테이블로 변환
$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 }}