1. 程式人生 > >數據的ID名生成新的引用索引樹

數據的ID名生成新的引用索引樹

style each pid php blog cnblogs fun array []

<?php
$arr=
[
    ‘0‘=>[
        "id"=>2,
        "name"=>"建材",
        "pid"=>0,
        "sort"=>50
    ],
    ‘1‘=>[
        "id"=>3,
        "name"=>"餐廳",
        "pid"=>1,
        "sort"=>50
    ],
    ‘2‘=>[
        "id"=>1,
        "name"=>"家居",
        "pid"=>0,
        "sort"=>50
    ]
, ‘3‘=>[ "id"=>4, "name"=>"客廳", "pid"=>1, "sort"=>50 ], ]; function genTree($items,$pid ="pid") { $map = []; $tree = []; foreach ($items as &$it){ $map[$it[‘id‘]] = &$it;//數據的ID名生成新的引用索引樹 } foreach ($items as &$it
){ $parent = &$map[$it[$pid]]; if($parent) { $parent[‘son‘][] = &$it; }else{ $tree[] = &$it; } } return $tree; } echo ‘<pre>‘;var_export(genTree($arr));‘<pre>‘; //array ( // 0 => // array ( // ‘id‘ => 2, // ‘name‘ => ‘建材‘, // ‘pid‘ => 0, // ‘sort‘ => 50, // ), // 1 => // array ( // ‘id‘ => 1, // ‘name‘ => ‘家居‘, // ‘pid‘ => 0, // ‘sort‘ => 50, // ‘son‘ => // array ( // 0 => // array ( // ‘id‘ => 3, // ‘name‘ => ‘餐廳‘, // ‘pid‘ => 1, // ‘sort‘ => 50, // ), // 1 => // array ( // ‘id‘ => 4, // ‘name‘ => ‘客廳‘, // ‘pid‘ => 1, // ‘sort‘ => 50, // ), // ), // ), //)

數據的ID名生成新的引用索引樹