簡體   English   中英

PHP循環遍歷數組

[英]PHP loop through arrays

我有一個如下所示的數組($ array):

Array
(
[0] => Array
    (
        [0] => A
        [1] => B
        [2] => C
    )

[1] => Array
    (
        [0] => 1
        [1] => 2
        [2] => 3
    )

[2] => Array
    (
        [0] => apple
        [1] => orange
        [2] => banana
    )

)

使用CreateXML我想獲取數組並創建一個XML文檔,但我遇到了一些問題。 我正在使用foreach從每個數組中獲取第一個值,因為我希望[0] A [0] 1 [0] apple位於一個元素中,依此類推。使用我現在擁有的代碼它可以用於一個元素,我該怎么做才能生成所有元素? 迷失在循環中,只是無法正確...感謝您的幫助!

public function CreateXML($array){

    foreach ($array as $arr) {
        $array2[] = $arr[0];
    }

    $xmlDoc = new DOMDocument();

    $root = $xmlDoc->appendChild(
      $xmlDoc->createElement("rootelement"));

    $tag = $root->appendChild(
          $xmlDoc->createElement("element"));

    $tag->appendChild(
       $xmlDoc->createElement("Letter", $array2[0]));

    $tag->appendChild(
       $xmlDoc->createElement("Number", $array2[1]));

    $tag->appendChild(
       $xmlDoc->createElement("Fruit", $array2[2]));

    header("Content-Type: text/plain");

    $xmlDoc->formatOutput = true;

    echo $xmlDoc->saveXML();
 }
$newArray = array();
for($i = 0; $i <= count($array[0]); $i++) {
    $newArray[] = array($array[0][$i], $array[1][$i], $array[2][$i]);
}

// Some XML here

foreach($newArray as $row) {
    $tag->appendChild(
       $xmlDoc->createElement("Letter", $row[0]));

    $tag->appendChild(
       $xmlDoc->createElement("Number", $row[1]));

    $tag->appendChild(
       $xmlDoc->createElement("Fruit", $row[2]));
}

// Some more XML and output

只有當每個子數組具有完全相同數量的元素時,這才有效

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM