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

Asked

Viewed 479 times

2

I’m making this code that has 2 foreach’s and carries 350 properties with more or less 3500 image links, I didn’t really call the photos, just the links, it all loads in half a second.

The variable $array stores contents of a XML. Inside this XML has several information including arrays of information such as Media which stores all images of the property.

In the case below, the second array magpie $imovel->Media->Item and makes a listing of the photos that are on 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>";
}

Result produced:

inserir a descrição da imagem aqui

  • I guess not because your images bring multiple records of another object

  • @Marcosbrinner then qier say that the two foreachs in this way are correct.

  • It’s okay to use one loop inside another. One thing you can do to improve the delivery of data is to create a buffer (ob_start()/ob_end_flush()) to deliver everything at once to the browser. Perhaps "apparent more performance". @Emersonbarcellos think it is not valid for this case since $imovel->Media->Item is from array of the first loop.

1 answer

0

An alternative way is to store the HTML content and print (echo) everything at the end, so you can use the function implode in place of foreach intern.

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 way the code becomes cleaner and more elegant. With regard to performance, it would be good for you to test both versions and post the result.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.