How do I format Nested Set Model data into an array?

前端 未结 5 1390
长发绾君心
长发绾君心 2020-12-09 14:18

Let\'s dig in the main problem right away, I have the input like this

$category = array(
  \'A\' => array(\'left\' => 1, \'right\' => 8),
  \'B\' =&         


        
5条回答
  •  渐次进展
    2020-12-09 14:43

    Another solution, without recursion (test please)

    $result = array();
    
        foreach($category as $key => $value) {
    
            /*Get current row index*/
            $i = count($result);
    
            if($i == 0) {
                $result[] = array($key);
            } else {
    
                $iParent = -1;
    
                /*Find parent index*/
                for($j = count($result[$i-1]) - 1; $j >= 0; $j--) {
                    if($value['left'] > $category[$result[$i-1][$j]]['left'] 
                        && $value['right'] < $category[$result[$i-1][$j]]['right']) {
                        $iParent = $j;
                        break;
                    }
                }
    
                if($iParent == -1) { $result[] = array($key);}
    
                if($iParent == count($result[$i-1]) - 1) {
                    // append to last
                    $result[$i-1][] = $key;
                } else {
                    // make new list
                    $result[$i] = array_slice($result[$i-1], 0, $iParent + 1);
                    $result[$i][] = $key;
                }
            }
        }
    
        print_r($result);
    

提交回复
热议问题