Php 从按parentID排序的数组到url的类别

Php 从按parentID排序的数组到url的类别,php,arrays,tree,categories,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'), arra

我有这个阵列:

$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[9]调用link并获得路径“Category D/Subcategory i”
谢谢您的建议。

下面的功能应该适合您

注意:此函数假定数组项已排序,因此一个项不依赖于数组中较低的另一个项(即已排序)

$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')
);
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;
}