Convert flat array to the multi-dimensional

后端 未结 3 728
Happy的楠姐
Happy的楠姐 2020-11-27 04:15

I have an array with tree data (by parent id). I want to convert it to multidimensional array. What is the best way to achieve that? Is there any short function for that?

3条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-11-27 05:02

    I was looking for an example of how to do this, with categories. This example assumes that parents will always have a parent id of '0'. The example is using ZF2.

    No references, or recursion. The trick is in the output, you look for the [0] index, and for the children, you specify the parent_id as the index.

    $categoryLookup = $this->getCategoryLookup($associateById=true);
    
    if ($assignedCategories) {          
        $categoryHeirarchy = array();
        foreach($assignedCategories as $assignedCategory) {
            $child = $categoryLookup[$assignedCategory->category_id];
            $parent = $categoryLookup[$child->parent_id];               
            $categoryHeirarchy[$child->parent_id][] = $categoryLookup[$child->category_id];
            $categoryHeirarchy[$parent->parent_id][$parent->category_id] = $categoryLookup[$parent->category_id];
        }           
    
        return $categoryHeirarchy;  
    }
    
    
    

    Categories

    categoryHeirarchy[0] as $parent): ?>
    escapeHtml($parent->name); ?>
    categoryHeirarchy[$parent->category_id] as $child): ?>
    escapeHtml($child->name); ?>

提交回复
热议问题