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;

}

1
  • 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 instead of trying to stack up the elements yourself. Commented Aug 29, 2021 at 15:18

1 Answer 1

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;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.