3v4l.org

run code in 200+ php & hhvm versions
Bugs & Features
<?php $arr = array( 0 => array( "text" => "eventyrer", "children"=> array( 4 => array( "text" => "news", "children"=> array( 1=> array("text"=>"a") ) ), 5 => array( "text" => "nyheter", "children"=> array( 1=> array("text"=>"b") ) ) ) ), 1 => array( "text" => "eventyrer2017", "children"=> array( 6 => array( "text" => "news", "children"=> array( 1=> array("text"=>"c") ) ), 8 => array( "text" => "nyheter", "children"=> array( 1=> array("text"=>"d") ) ) ) ) ); class Tree { private $data; private $html; public function buildTree(array $data, $parent_id) { $this->data = $data; $this->html = []; foreach ($data as $key => $value) { $this->process($key, $value); } return $this->html; } private function process($parentKey, $value) { var_dump($value); $this->html[$parentKey] = $value['text']; if (array_key_exists('children', $value) && count($value['children'])) { $this->html[$parentKey] .= '/'; $this->process($parentKey, $value['children']); } } } $tree = new Tree(); $ul = $tree->buildTree($arr, 0); var_dump( $ul);
based on GQ2AR
Output for 5.6.38 - 7.3.0rc3
array(2) { ["text"]=> string(9) "eventyrer" ["children"]=> array(2) { [4]=> array(2) { ["text"]=> string(4) "news" ["children"]=> array(1) { [1]=> array(1) { ["text"]=> string(1) "a" } } } [5]=> array(2) { ["text"]=> string(7) "nyheter" ["children"]=> array(1) { [1]=> array(1) { ["text"]=> string(1) "b" } } } } } array(2) { [4]=> array(2) { ["text"]=> string(4) "news" ["children"]=> array(1) { [1]=> array(1) { ["text"]=> string(1) "a" } } } [5]=> array(2) { ["text"]=> string(7) "nyheter" ["children"]=> array(1) { [1]=> array(1) { ["text"]=> string(1) "b" } } } } Notice: Undefined index: text in /in/eViFa on line 65 array(2) { ["text"]=> string(13) "eventyrer2017" ["children"]=> array(2) { [6]=> array(2) { ["text"]=> string(4) "news" ["children"]=> array(1) { [1]=> array(1) { ["text"]=> string(1) "c" } } } [8]=> array(2) { ["text"]=> string(7) "nyheter" ["children"]=> array(1) { [1]=> array(1) { ["text"]=> string(1) "d" } } } } } array(2) { [6]=> array(2) { ["text"]=> string(4) "news" ["children"]=> array(1) { [1]=> array(1) { ["text"]=> string(1) "c" } } } [8]=> array(2) { ["text"]=> string(7) "nyheter" ["children"]=> array(1) { [1]=> array(1) { ["text"]=> string(1) "d" } } } } Notice: Undefined index: text in /in/eViFa on line 65 array(2) { [0]=> NULL [1]=> NULL }