简体   繁体   中英

My foreach loop with 2 variables doesn't work

$lines = file("C:/xampp/htdocs/results/result5.csv");
$lines1 = file("C:/xampp/htdocs/results/result7.csv");
foreach(array_combine($lines, $lines1) as $line => $line1)
    echo "<a href='www.google.de/webhp?hl=de#hl=de&q=" . trim($line1) . "'><img src='" . trim($line) . "' style="width:200px;height:100px;" /></a>"

Hi guys, I am trying to get a clickable image with ingredients from 2 .csv files. I want to create aa row of images (first csv) that - when is clicked - shows a google search(with data from the second csv).

The CSVs both have the same amout of lines.

When processing each csv seperatly I get a row of images and a row of links, but thats not what i want.

$lines = file("C:/xampp/htdocs/results/result5.csv");
$lines1 = file("C:/xampp/htdocs/results/result7.csv");
foreach($lines as $line)
    echo "<p><img src='" . trim($line) . "'></p>";
    foreach($lines1 as $line1)
        echo "<a href='www.google.de/webhp?hl=de#hl=de&q=" . trim($line1) . "'>CLICK</a>";

Where does it go wrong?

You can avoid the array_combine by using indexes - assuming the files are loaded indexed 0, 1, 2, 3....

$lines = file("C:/xampp/htdocs/results/result5.csv");
$lines1 = file("C:/xampp/htdocs/results/result7.csv");
foreach($lines as $i=>$line) // $i is the index
{
    echo "<a href='www.google.de/webhp?hl=de#hl=de&q=" . trim($lines1[$i]) . "'>";
    echo "<img src='" . trim($line) . "'>";
    echo "</a>";
}

Perhaps you mean

foreach(array_merge($lines, $lines1) as $line) { ... }

rather than array_combine()

Assumes that each line in each of the files is a single entry

Alternatively:

$mi = new MultipleIterator();
$mi->attachIterator(new ArrayIterator($lines));
$mi->attachIterator(new ArrayIterator($lines1));
foreach($mi as list($line, $line1)) {
    echo $line, ' - ', $line1, PHP_EOL;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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