Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP loop through arrays

Tags:

arrays

php

xml

I have an array ($array) that looks like this:

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. 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? 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();
 }
like image 629
ana Avatar asked Nov 13 '22 16:11

ana


1 Answers

$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

like image 103
Alex Rashkov Avatar answered Nov 15 '22 07:11

Alex Rashkov