【问题标题】:PHP loop Foreach + WhilePHP 循环 Foreach + While
【发布时间】:2015-07-03 23:10:50
【问题描述】:

我不知道为什么结果是返回重复的行。 此代码尝试获取每个列和行数据。

$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

【问题讨论】:

  • 我相信foreach 循环应该在主循环之外,因为它们不依赖于$matkul。这就像你有一个循环,总是收获相同的页面,但只打印第一个元素。
  • $dom->find 如何在 while 循环的每次迭代中得到不同的结果?
  • 谢谢你,它工作。而且重量更轻。
  • 我可以把它写成答案,你会批准吗?
  • @OfirBaruch 是的,请。

标签: php loops foreach while-loop fetch


【解决方案1】:

由于您的 2 个 foreach loops$dom-&gt;find 位于单个 while loop 中,因此您基本上是在遍历所有符合您的条件的 DOM 元素 (td[...])。这些循环在 while 循环中没有依赖关系,所以我会说它效率不高。

此外,您对$s,$n 结果使用常量键,因此您始终会得到相同的结果。

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

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

确保检查$i$i+1 是否在数组的限制范围内。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-10-19
    • 2018-02-09
    • 2017-05-28
    • 2012-10-02
    • 2018-05-20
    • 2014-04-15
    • 1970-01-01
    • 2013-10-01
    相关资源
    最近更新 更多