function recursive($array, $level = 0) { foreach($array as $key => $value) { if (!is_array($value) && $key == "tag") { echo str_repeat(" ", $level), "[".$value."]", ''; } //If $value is an array. if(is_array($value)) { //We need to loop through it. recursive($value, $level + 1); } else { //It is not an array, so print it out. if ($key == "tag") { echo "[/".$value."]", '<br>'; } } } } $tree_2 = recursive($tree_1); echo $tree_2;