数组中的类别按parentID排序到url

时间:2013-10-31 21:31:06

标签: php arrays tree categories

我有这个数组:

$categories = array(
    array('id' => 1,  'parent' => 0, 'name' => 'Category A'),
    array('id' => 2,  'parent' => 0, 'name' => 'Category B'),
    array('id' => 3,  'parent' => 0, 'name' => 'Category C'),
    array('id' => 4,  'parent' => 0, 'name' => 'Category D'),
    array('id' => 5,  'parent' => 0, 'name' => 'Category E'),
    array('id' => 6,  'parent' => 2, 'name' => 'Subcategory F'),
    array('id' => 7,  'parent' => 2, 'name' => 'Subcategory G'),
    array('id' => 8,  'parent' => 3, 'name' => 'Subcategory H'),
    array('id' => 9,  'parent' => 4, 'name' => 'Subcategory I'),
    array('id' => 10, 'parent' => 9, 'name' => 'Subcategory J'),
);

结果我需要这个: (对于$ categories数组中的每个类别,只需要一个完整结构的链接)

$result = array(
    '10' => 'Category D/Subcategory I/Subcategory J',
    '9' => 'Category D/Subcategory I',
    '8' => 'Category C/Subcategory H',
    '7' => 'Category B/Subcategory G',
    '6' => 'Category B/Subcategory F',
    '5' => 'Category E',
    '4' => 'Category D',
    '3' => 'Category C',
    '2' => 'Category B',
    '1' => 'Category A')
);

之后我可以通过$ result [9]调用链接并获取路径“Category D / Subcategory I” 谢谢你的建议。

1 个答案:

答案 0 :(得分:1)

以下功能应该适合您。

注意:此函数假定数组项是有序的,因此项不依赖于数组中更下方的另一项(即已topologically sorted)。

function build_structure($arr) {
    $output = array();
    foreach ($arr as $item) {
        $value = ($item['parent'] == 0) ? $item['name'] :
                     $output[$item['parent']] . '/' . $item['name'];
        $output[$item['id']] = $value;
    }
    return $output;
}