php foreach iki loop

0 Cevap php

Benim veritabanından bazı verileri döngü çalışıyorum ama iki kez çıktısı.

$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=0;

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++;
}

Çıkarılması:

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

Biraz daha oynamak ve aşağıdakileri denedim etmedi.

$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=0;

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++;
}

İlginç olan, bu altında çıktılar ki:

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.

Bu çok uzun adamcağız beni olmuştur, bu yüzden herkes yardımcı olabilir, ben çok minnettar olacaktır!

0 Cevap