PHP循环Foreach + While

时间:2015-04-25 08:30:20

标签: php loops foreach while-loop fetch

我不知道为什么结果会返回重复的行。 这段代码试图获取每个coloumn&行数据。

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

我声明了将数据coloumn移动到变量

的数组
$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

1 个答案:

答案 0 :(得分:0)

由于foreach loops $dom->find while loop位于一个td[...]中,您基本上会遍历所有符合条件的DOM元素($s )。那些循环在while循环中没有依赖性,所以我认为它没有效率。

此外,您为$nwhile结果使用常量键,因此您始终可以获得相同的结果。

为了获得更好的性能和工作解决方案,您应该将这两个foreach循环放在$s循环之外(和上方)。因此$n$s[$i]数组将包含所有需要的元素,并且在主循环中只需设置一个计数器并增加它。

请注意,为了获得以下2个元素,您应该执行以下操作:$s[$i+1]$i

请务必检查$i+1$candname是否在数组范围内。