【问题标题】:Categories from array sorted by parentID to url从按 parentID 排序的数组到 url 的类别
【发布时间】:2013-10-31 21:31:06
【问题描述】:

我有这个数组:

$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] 调用链接并获取路径“D 类/子类 I” 谢谢你的建议。

【问题讨论】:

    标签: php arrays tree categories


    【解决方案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;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-06-01
      • 2019-08-20
      • 2023-03-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-04
      相关资源
      最近更新 更多