bademeister bademeister - 4 months ago 4
PHP Question

Parse multidimensional array in PHP

main goal: the whole array should be converted to XML later.

I want to do following things:
For every key (e.g. 12772) data has to be fetched from a database so I can not convert it simply. The fetched data will be attributes of a tag.

My idea was to combine the deepest childs to one xml string. But how can I detect if I am in the deepest level? I have thought kind of a do...while-loop but I don't know how to check exactly if the element has a child or not.

The array depth can vary as you can see:

Array
(
[12772]=>Array
(
[16563]=>Array
(
[0] => <xml>Information 1</xml>
[1] => <xml>Information 2</xml>
)
)

[16532]=>Array
(
[0] => <xml>Information 1</xml>
[1] => <xml>Information 2</xml>
)

)


Any help is very appreciated!

/edit:
Output should be:

<xml>
<testsuite id='12772' name='fetched from database'>
<testsuite id='16563' name='fetched from database'>
<testcase id='0'>Information 1</testcase>
<testcase id='1'>Information 2</testcase>
</testsuite>
</testsuite>
<testsuite id='16532' name='fetched from database'>
<testcase id='0'>Information 1</testcase>
<testcase id='1'>Information 2</testcase>
</testsuite>

Answer

Recursive is the best to loop into tree like structure. Basically, a recursive function is a function that call itself. By example:

$input = Array
(
    12772=>Array
        (
            16563=>Array
                (
                    0 => '<xml>Information 1</xml>',
                    1 => '<xml>Information 2</xml>'
                )
        ),
    16532=>Array
        (
            0 => '<xml>Information 1</xml>',
            1 => '<xml>Information 2</xml>'
        )

);

$xml = "";

recursiveFunction($xml, $input);

var_dump($xml);

function recursiveFunction(&$output, $node, $id = 0, $level = 0)
{

    if (is_array($node)) {

        if ($level === 0) {

             $output .= "<xml>" . PHP_EOL;

         } else {

            $output .= str_repeat("\t", $level) . "<testsuite id='" .  $id . " name='fetched from database'>" . PHP_EOL;
        } 

        foreach ($node as $id => $newNode) {
            recursiveFunction($output, $newNode, $id, $level + 1);
        }

        if ($level === 0) {

             $output .= "</xml>";

         } else {

            $output .= str_repeat("\t", $level) . "</testsuite>" . PHP_EOL;
        } 

    } else {

        $output .= str_repeat("\t", $level) . "<testcase id='" .  $id . "'>" . $node . "</testcase>" . PHP_EOL;
    }
}

You can test it here: http://sandbox.onlinephpfunctions.com/code/dcabd9ffccc1a05621d8a21ef4b14f29b4a765ca

Comments