ホームページ >バックエンド開発 >PHPチュートリアル >ツリー構造 (州や都市など)、ツリー構造の州と都市の生成_PHP チュートリアル
<br /><?<span>php </span><span>header</span>("Content-type: text/html; charset=utf-8"<span>); </span><span>function</span> generateTree(<span>$items</span><span>) { </span><span>$tree</span> = <span>array</span><span>(); </span><span>foreach</span>(<span>$items</span> <span>as</span> <span>$item</span><span>){ </span><span>if</span>(<span>isset</span>(<span>$items</span>[<span>$item</span>['pid'<span>]])){ </span><span>$items</span>[<span>$item</span>['pid']]['son'][] = &<span>$items</span>[<span>$item</span>['id'<span>]]; }</span><span>else</span><span>{ </span><span>$tree</span>[] = &<span>$items</span>[<span>$item</span>['id'<span>]]; } } </span><span>return</span> <span>$tree</span><span>; }<br />//需要注意的一点,数组的key值必须与id值保持一致 </span><span>$items</span> = <span>array</span><span>( </span>1 => <span>array</span>('id' => 1, 'pid' => 0, 'name' => '安徽省'), 2 => <span>array</span>('id' => 2, 'pid' => 0, 'name' => '浙江省'), 3 => <span>array</span>('id' => 3, 'pid' => 1, 'name' => '合肥市'), 4 => <span>array</span>('id' => 4, 'pid' => 3, 'name' => '长丰县'), 5 => <span>array</span>('id' => 5, 'pid' => 1, 'name' => '安庆市'),<span> ); </span><span>echo</span> "<pre class="brush:php;toolbar:false">"<span>; </span><span>print_r</span>(generateTree(<span>$items</span>));
上記メソッドの最適化:
8b417d5f02e291449c9b85aff55cc457 配列('id' => 1, 'pid' => 0, 'name' => '安徽省'), 2 => 配列('id' => 2, 'pid' => 0, 'name' => '浙江省'), 3 => 配列('id' => 3, 'pid' => 1, 'name' => '合肥市'), 4 => 配列('id' => 4, 'pid' => 3, 'name' => '長豊県'), 5 => 配列('id' => 5, 'pid' => 1, 'name' => '安慶市'), ); エコー「e03b848252eb9375d56be284e690e873」; print_r(generateTree($items)); コードを表示
結果:
)