0

I wrote a simple php function to walk over a multidimensional array and print its content in a preformatted way. But the function doesn't go deep and only adds first-level leaf nodes to the text.

Can anyone please help to figure out the problem and the solution?

function LOP($arrayItself, $txt){
    foreach($arrayItself as $fieldName=>$fieldValue){       
            if(is_array($fieldValue)){
                    LOP($fieldValue, $txt);
            }
            else {
                    $txt .= "<$fieldName>  $fieldValue  </$fieldName>";
            }
    }
    return $txt;

}

Hamlet Kraskian
  • 683
  • 9
  • 11
  • 1
    Going out on a limb: since it appears you're trying to build an XML document here, I would recommend generating such a document using [a proper XML building library](https://stackoverflow.com/questions/486757/how-to-generate-xml-file-dynamically-using-php) instead of trying to stack up the elements yourself. – esqew Aug 29 '21 at 15:18

1 Answers1

3

In your if(is_array($fieldValue)) block, you need to capture the return value of your recursive call to LOP():

function LOP($arrayItself, $txt){
    foreach($arrayItself as $fieldName=>$fieldValue){       
            if(is_array($fieldValue)){
                    $txt = LOP($fieldValue, $txt);
            }
            else {
                    $txt .= "<$fieldName>  $fieldValue  </$fieldName>";
            }
    }
    return $txt;
}
esqew
  • 42,425
  • 27
  • 92
  • 132