PHP depth 테이블을 parent_id 테이블로 변환

Jmnote (토론 | 기여)님의 2020년 5월 25일 (월) 01:50 판 (새 문서: ==개요== {{DISPLAYTITLE:PHP depth 테이블을 parent_id 테이블로 변환}} <source lang='php' run> $table1 = [ ['id'=> 1, 'value'=>'/' , 'depth'=>0], ['id'=> 2, 'value'=...)
(차이) ← 이전 판 | 최신판 (차이) | 다음 판 → (차이)

1 개요

$table1 = [
  ['id'=> 1, 'value'=>'/'    , 'depth'=>0],
  ['id'=> 2, 'value'=>'bin'  , 'depth'=>1],
  ['id'=> 3, 'value'=>'etc'  , 'depth'=>1],
  ['id'=> 4, 'value'=>'opt'  , 'depth'=>1],
  ['id'=> 5, 'value'=>'usr'  , 'depth'=>1],
  ['id'=> 6, 'value'=>'bin'  , 'depth'=>2],
  ['id'=> 7, 'value'=>'local', 'depth'=>2],
  ['id'=> 8, 'value'=>'sbin' , 'depth'=>2],
  ['id'=> 9, 'value'=>'share', 'depth'=>2],
  ['id'=>10, 'value'=>'var'  , 'depth'=>1],
  ['id'=>11, 'value'=>'log'  , 'depth'=>2],
];

$table2 = [];
$temp_parent_ids = [];
foreach($table1 as $row) {
  $id = $row['id'];
  $depth = $row['depth'];
  $row['parent_id'] = $temp_parent_ids[$depth-1] ?: 0;
  $temp_parent_ids[$depth] = $id;
  $table2[] = $row;
}

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

2 같이 보기

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