2016-07-26 116 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