【问题标题】:PHP loop through arraysPHP循环遍历数组
【发布时间】:2012-11-14 06:07:39
【问题描述】:

我有一个如下所示的数组 ($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();
 }

【问题讨论】:

    标签: php xml arrays


    【解决方案1】:
    $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
    

    只有当每个子数组的元素数量完全相同时才有效

    【讨论】: