2016-07-26 115 views
-1

主要目标:整个数组应该稍后转换为XML。在PHP中解析多维数组

我想做以下事情: 对于每个密钥(例如12772)数据都必须从数据库中获取,因此我无法简单地将其转换。获取的数据将是标签的属性。

我的想法是将最深的小孩合并到一个xml字符串中。但是,如何检测我是否处于最深层次?我曾经想过做... while循环,但我不知道如何检查元素是否有孩子。

该阵列的深度可以改变,你可以看到:

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> 
<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> 

回答

1

递归是最好循环到像结构树。基本上,递归函数是一个自我调用的函数。举例:

$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; 
    } 
} 

你可以在这里进行测试:http://sandbox.onlinephpfunctions.com/code/dcabd9ffccc1a05621d8a21ef4b14f29b4a765ca

+0

感谢您的输入。但我怎么知道我在哪个级别/路径?我想将不是数组的$节点“合并”在一起,但合并后的值应保持在同一水平。就像删除旧值并设置一个新值。我的例子XML可能不是最好的,“信息1”应该是一个单独的标签,我希望这些标签在一个数组值。 – bademeister

+0

我更新了我的代码,以便您可以获得关卡和路径。现在,我不太确定我是否理解你想要输出的东西,它是一个数组还是xml? http://sandbox.onlinephpfunctions.com/code/a047ef69786391d8ece1cfbad9a24a8c72f2a428 –

+0

输出后面应该是XML,我已经将格式添加到主要问题! – bademeister