Creating a multilevel array using parentIds in PHP

后端 未结 4 627
遇见更好的自我
遇见更好的自我 2020-12-15 01:01

I\'m trying to setup a list that can have multiple levels, using parentId to define its parent. The first item\'s parentId is NULL. Example of some

4条回答
  •  一个人的身影
    2020-12-15 01:10

    You may not need a new solution anymore, but this might come in handy for other users:

    // ! assuming $elements is built like: Array( id1 => Array(/*parameters*/) , ...)
    
    function buildTree($elements) {
    
        $e = Array(0 => Array()); // elements array
        $r = Array(0 =>& Array()); // reference array
    
        while ($elements) {// repeat till $elements is empty
    
            // loop through (remaining) elements
            foreach ($elements as $id => $element) {
    
                $pid = $element['parentId']; // shortcut
    
                if (array_key_exists($pid,$r)) { // parent already parsed -> can add this element
    
                    // use parent's reference to elements array to add this element ( $r[$pid] =& $e[path][to][$pid] )
                    $r[$pid] ['elements'][$id] = $element;
    
                    // create reference for this element using parent's reference
                    $r[$id] =& $r[$pid]['elements'][$id];
    
                    // unset current element in input array in order to limit while-loop
                    unset($elements[$id]);
    
                }
    
            }
        }
    
    return $e; // or whatever you need, the reference array can be useful if you need to fetch an element only knowing its id
    
    }
    

    What it does:

    • declare an array for the results ($e) and add a root element (0/null)
    • declare an array for the references ($r) and already reference $r[0] to $e[0]
    • loop through the input array till it's empty
      • do for each element:
      • check if parent already is handled, if so, you know where this element belongs and can add it
        (this is what prevented me from getting it working the first couple attempts and why the while loop is needed)
      • add the current element using parent's reference (note the & after = !)
      • create a new reference using the parent's reference
      • unset the current element from the input array
        (you can leave this if you like infinite while loops ;) )
    • of cource return what you need!

    The benefits of this method are:

    • you reduce the amount of foreach loops (you assign the most you can from what you know at the moment)
    • each loop gets shorter because you unset parsed elements in the input array ($elements)
    • you can also return the reference array and be able to quickly get the element's parameters assuming you know it's id

    In other words: it should be faster (I haven't tested it!), at least for more complex tasks like the one I use it for.

提交回复
热议问题