簡體   English   中英

PHP循環Foreach + While

[英]PHP loop Foreach + While

我不知道為什么結果會返回重復的行。 這段代碼試圖獲取每個列和行數據。

$n=array();
$s=array();

我聲明了將數據列移動到變量的數組

$i =0;
$x =0;
$matkul = 0;
while ($matkul<$ttlrow){    
        //try to fecth all coloumns data every row.
            foreach($dom->find('td[style="text-align:left;"]') as $b) {
                $n[$x]=$b->plaintext;
                $x++;                    
            }
        //try to show the data before insert to Database
        $k_mk= $n[0];
        $n_mk= $n[1];
        echo $k_mk . ' | ';
        echo $n_mk. ' | ';
            //try to fecth all coloumns data every row.
            foreach($dom->find('td[style="text-align:center;"]') as $a) {
                $s[$i]=$a->plaintext;
                $i++;
            }
        //try to show the data before insert to Database
        $sks= $s[0];
        $grd = $s[1];
        $bbt = $s[2];
        $nl = $s[3];
        $uid = $uid;
        echo $sks . ' | ';
        echo $grd. ' | ';
        echo $nl. '<br>';
        /*
       $sql = "INSERT INTO fokusipk_ks.jadwal (`uid`, `kd_mk`, `kd_sms`,  
       `nm_mk`, `nm_dsn`, `kd_kls`, `hari`, `jam`) 

       VALUES ('$uid', '$mk', '$sms', '$nmk', '$nmd', '$kls', '$hari', 
       '$jam');";
            if ($conn->query($sql) === TRUE) {
                #echo '.';
            }
        */
        $matkul++;
       //refresh the value to re-start fetching from the first coloumn
        $i=0;
        $x=0;
}


Code   | Courses                       | W | G | V

the results something like this:

TPLB02 | PENGANTAR TEKNOLOGI INFORMASI | 2 | A | 8

TPLB02 | PENGANTAR TEKNOLOGI INFORMASI | 2 | A | 8

TPLB02 | PENGANTAR TEKNOLOGI INFORMASI | 2 | A | 8

TPLB02 | PENGANTAR TEKNOLOGI INFORMASI | 2 | A | 8

TPLB02 | PENGANTAR TEKNOLOGI INFORMASI | 2 | A | 8

TPLB02 | PENGANTAR TEKNOLOGI INFORMASI | 2 | A | 8

TPLB02 | PENGANTAR TEKNOLOGI INFORMASI | 2 | A | 8

TPLB02 | PENGANTAR TEKNOLOGI INFORMASI | 2 | A | 8

TPLB02 | PENGANTAR TEKNOLOGI INFORMASI | 2 | A | 8

由於$dom->find 2個foreach loops位於單個while loop ,因此基本上可以遍歷所有可滿足您條件的DOM元素( td[...] )。 這些循環在while循環中沒有依賴關系,所以我會說這沒有效率。

此外,您在$s$n結果中使用了常量鍵,因此您始終可以獲得相同的結果。

為了獲得更好的性能和可行的解決方案,您應該將這兩個foreach循環放在while循環之外(或之上)。 因此, $s$n數組將包含所有所需的元素,並且在您的主循環中只需設置一個計數器並增加它。

請記住,為了獲得2個以下元素,您應該執行以下操作: $s[$i]$s[$i+1]

確保檢查$i$i+1是否在數組限制的范圍內。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM