php foreach looping twice
Posted
by
Jack
on Stack Overflow
See other posts from Stack Overflow
or by Jack
Published on 2010-12-29T19:01:32Z
Indexed on
2011/01/04
10:54 UTC
Read the original article
Hit count: 201
Hi, I am trying to loop through some data from my database but it is outputting it twice.
$fields = 'field1, field2, field3, field4';
$idFields = 'id_field1, id_field2, id_field3, id_field4';
$tables = 'table1, table2, table3, table4';
$table = explode(', ', $tables);
$field = explode(', ', $fields);
$id = explode(', ', $idFields);
$str = 'Egg';
$i=1;
while ($i<4) {
$f = $field[$i];
$idd = $id[$i];
$sql = $writeConn->select()->from($table[$i], array($f, $idd))->where($f . " LIKE ?", '%' . $str . '%');
$string = '<a title="' . $str . '" href="' . $currentProductUrl . '">' . $str . '</a>';
$result = $writeConn->fetchAssoc($sql);
foreach ($result as $row) {
echo 'Success! Found ' . $str . ' in ' . $f . '. ID: ' . $row[$idd] . '.<br>';
}
$i++;
}
Outputting:
Success! Found Egg in field3. ID: 5.
Success! Found Egg in field3. ID: 5.
Could someone please explain why it is looping through both the indexed and associative values?
UPDATE
I did some more playing around and tried the following.
$fields = 'field1, field2, field3, field4';
$idFields = 'id_field1, id_field2, id_field3, id_field4';
$tables = 'table1, table2, table3, table4';
$table = explode(', ', $tables);
$field = explode(', ', $fields);
$id = explode(', ', $idFields);
$str = 'Egg';
$i=1;
while ($i<4) {
$f = $field[$i];
$idd = $id[$i];
$sql = $writeConn->select()->from($table[$i], array($f, $idd))->where($f . " LIKE ?", '%' . $str . '%');
$string = '<a title="' . $str . '" href="' . $currentProductUrl . '">' . $str . '</a>';
$sth = $writeConn->prepare($sql);
$sth->execute();
$result = $sth->fetch(PDO::FETCH_ASSOC);
foreach ($result as $row) {
echo 'Success! Found ' . $str . ' in ' . $f . '. ID: ' . $row[$idd] . '.<br>';
}
$i++;
}
The interesting thing is that this outputs the below:
Success! Found Egg in field3. ID: E.
Success! Found Egg in field3. ID: E.
Success! Found Egg in field3. ID: 5.
Success! Found Egg in field3. ID: 5.
Success! Found Egg in field3. ID: E.
Success! Found Egg in field3. ID: E.
Success! Found Egg in field3. ID: 5.
Success! Found Egg in field3. ID: 5.
I have also tried adding $i
to the output and this outputs 2
as expected.
If I change fetch(PDO::FETCH_BOTH)
to fetch(PDO::FETCH_ASSOC)
the output is as follows:
Success! Found Egg in field3. ID: E.
Success! Found Egg in field3. ID: E.
Success! Found Egg in field3. ID: 5.
Success! Found Egg in field3. ID: 5.
This has been bugging me for too long, so if anyone could help I would be very appreciative!
© Stack Overflow or respective owner