简体   繁体   中英

Results of foreach loop prints multiple times

I am trying to split a delimited string of postcodes so that instead of it looking like this:

before:
row1: ST16,ST17,ST18,ST19,ST20
row2: AT16,AT17,AT18,AT19,AT20
row3: LL16,LL17,LL18,LL19,LL20

after:
row1: ST16
row2: ST17
row3: ST18 ...etc

each postcode will have its own individual row. I have managed to do this however when i run my code, it seems to be printing the array of postcodes by the number of elements it contains. For example, if there are 11 elements in the array it will print [ST16,ST17,ST18,ST19,...] 11 times. Does anyone know why that is?

if ($db_found) {

// Select all fields from bodyshops_master_network table
$SQL = "SELECT * FROM bodyshops_master_network";
$result = mysql_query($SQL);

while ( $db_field = mysql_fetch_assoc($result) ) {

    // Splits the arrays
    $row = explode(",", $db_field['postcodes_covered']);

    foreach ($row as $value) {
        print "<pre>";
        echo implode("<br>", $row);
        print "</pre>";    
    }

}

mysql_close($db_handle);

} else {

print "Database NOT Found ";
mysql_close($db_handle);
}

Your foreach loop is redundant and should simply be:

$text = implode('<br />', $row);
echo "<pre>$text</pre>";

If you insist on the loop, then it should be

echo '<pre>';
foreach($row as $value) {
    echo $value, '<br />';
}
echo '</pre>';

implode() does the exact opposite of explode() . Basically, it glues the entire array back together with whatever string you want (a <br> in this case). So the only code you would need to display the postcodes in order would be:

$row = explode(",", $db_field['postcodes_covered']);
echo implode("<br>", $row);

This will output all the postcodes with a line break between them. The reason you were getting the output 11 times is because there are 11 items in the array, so the implode() got called 11 times.

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