How can I improve this loop that has one foreach inside another?

2

I am making this code that has 2 foreach's and loads 350 properties with more or less 3500 image links , in fact I did not call the photos, only the links, this everything loads in half a second .

The variable $array stores content from a XML . Inside this XML has a lot of information including information arrays like Media that stores all the images of the property.

In the case below, the second array takes $imovel->Media->Item and makes a listing of the photos that are in the property.

<?php

$xml = simplexml_load_file("xml_vivareal.xml") or die("Error: Cannot create object");
$array = $xml->Listings->Listing;
$number = 1;

foreach ($array as $imovel) {
    echo $number++ ." - ". $imovel->ListingID . "<br>";
    echo $imovel->Title . "<br>";

    foreach ($imovel->Media->Item as $fotos) {
        echo $fotos . "<br>";
    }

    echo "<br>";
}
  

Output produced :

    
asked by anonymous 20.06.2016 / 20:41

1 answer

0

An alternative way is to store the HTML content and print everything at the end, so you can use the implode function instead of the foreach .

See the code below:

<?php
$xml = simplexml_load_file("xml_vivareal.xml") or die("Error: Cannot create object");
$array = $xml->Listings->Listing;
$number = 1;
$html = '';

foreach ($array as $imovel) {
    $html .= $number++ ." - ". $imovel->ListingID . "<br>";
    $html .= $imovel->Title . "<br>";

    $html .= implode("<br>", $imovel->Media->Item);

    $html .= "<br>";
}

echo $html;

?>

I believe that this way the code will be cleaner and more elegant. Regarding the performance, it would be good if you did a test in both versions and post the result.

    
18.07.2016 / 22:04