PHP言語で配列の要素を再帰的に置き換える方法

1.配列の定義

$items = array(

1 => array('id’ => 1, 'pid’ => 0, 'name’ => '神奈川’),
2 => array('id’ => 2, 'pid’ => 0, 'name’ => '埼玉’),
3 => array('id’ => 3, 'pid’ => 1, 'name’ => '東京’),
4 => array('id’ => 4, 'pid’ => 2, 'name’ => '大阪’),
5 => array('id’ => 5, 'pid’ => 2, 'name’ => '名古屋’),
6 => array('id’ => 6, 'pid’ => 4, 'name’ => '福岡’),
7 => array('id’ => 7, 'pid’ => 4, 'name’ => '沖縄’),
8 => array('id’ => 8, 'pid’ => 6, 'name’ => '茨城’),
9 => array('id’ => 9, 'pid’ => 7, 'name’ => '千葉’),
10 => array('id’ => 10, 'pid’ => 8, 'name’ => '東京工業大学’),
11 => array('id’ => 11, 'pid’ => 9, 'name’ => '慶応大学’),
12 => array('id’ => 12, 'pid’ => 8, 'name’ => '埼玉大学’),
13 => array('id’ => 13, 'pid’ => 1, 'name’ => '横浜’),
14 => array('id’ => 14, 'pid’ => 13, 'name’ => '静岡’),
15 => array('id’ => 15, 'pid’ => 13, 'name’ => '宇都宮’),
16 => array('id’ => 16, 'pid’ => 14, 'name’ => '和田’),
17 => array('id’ => 17, 'pid’ => 14, 'name’ => '新宿’),
18 => array('id’ => 18, 'pid’ => 16, 'name’ => '渋谷区’),
19 => array('id’ => 19, 'pid’ => 16, 'name’ => '五反田’),
);

2.方法1;
function genTree5($items) {
foreach ($items as $item)
$items[$item['pid’]]['son’][$item['id’]] = &$items[$item['id’]];
return isset($items[0]['son’]) ? $items[0]['son’] : array();
}

3.方法2:
function findChild($arr,$id){
$childs=array();
foreach ($arr as $k => $v){
if($v['pid’]== $id){
$childs[]=$v;
}
}
// echo “<pre>";print_r($childs);die();
return $childs;
}

function build_tree($root_id){
global $items;
$childs =array();
$childs=findChild($items,$root_id);
// print_r($childs);
// die();
if(empty($childs)){
return null;
}
foreach ($childs as $k => $v){
$rescurTree=build_tree($v['id’]);
if( null != $rescurTree){
$childs[$k]['son’]=$rescurTree;
}
}
return $childs;
}

Development

Posted by arkgame