PHP unlimited classification



<?php $items = [     ['id' => 1, 'pid' => 0, 'name' => 'China'],     ['id' => 2, 'pid' => 0, 'name' => 'Japan'],     ['id' => 3, 'pid' => 1, 'name' => 'Diaoyu islands'],     ['id' => 4, 'pid' => 2, 'name' => 'Doraemon'],     ['id' => 5, 'pid' => 1, 'name' => 'Taiwan'],     ['id' => 6, 'pid' => 5, 'name' => 'Taipei'],     ['id' => 7, 'pid' => 6, 'name' => 'Taipei 101'], ]; function generateTree($array) {     // First step, would classify id as array key     $items = [];     foreach ($array as $item) {         $items[$item['id']] = $item;     }     // Second part, Use reference, add each item to the parent children Array     $tree = [];     foreach ($items as $key => $item) {         if (isset($items[$item['pid']])) {             $items[$item['pid']]['children'][] = &$items[$key];         } else {             $tree[] = &$items[$key];         }     }     return $tree; } print_r(generateTree($items));

標籤:  Release    PHP    Code    en    更多