简体   繁体   English

PHP循环遍历数组

[英]PHP loop through arrays

I have an array ($array) that looks like this: 我有一个如下所示的数组($ 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
    )

)

With CreateXML I want to take the array and create a XML document, but I'm having some problems. 使用CreateXML我想获取数组并创建一个XML文档,但我遇到了一些问题。 I'm using the foreach to get the first value from each array, because I want the [0]A [0]1 [0]apple to be in one element and so on.. With the code I have now it works for one element, how can I do it so I generates all the elements? 我正在使用foreach从每个数组中获取第一个值,因为我希望[0] A [0] 1 [0] apple位于一个元素中,依此类推。使用我现在拥有的代码它可以用于一个元素,我该怎么做才能生成所有元素? Got lost in loops and just can't get it right.. Thanks for help! 迷失在循环中,只是无法正确...感谢您的帮助!

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

That will work only if each of the sub arrays has exactly same number of elements 只有当每个子数组具有完全相同数量的元素时,这才有效

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM