php foreach 问题
我正在使用 simple_html_dom_helper,因此进行了一些屏幕抓取,但遇到了一些错误。
第二个 foreach 运行 4 次(因为 sizeof($pages) == 4
),而它应该只运行一次。我从示例脚本中获取了此代码,其中 table.result-liste
在页面上出现了多次。就我而言,它只发生一次,所以恕我直言,不需要 foreach。 print_r($data)
打印相同的内容 4 次,但没有必要这样做。
再往下,我试图在没有 foreach 的情况下做同样的事情,但它只是打印出 no
,所以似乎有不同的响应,我不确定为什么。
foreach( $pages as $page )
{
$p = $this->create_url($codes[0], $price, $page); //pass page number along
$p_html = file_get_html($p);
$row = $p_html->find("table[class=result-liste] tr");
//RUNS OK BUT NO NEED TO DO IT FOUR TIMES.
//CLASS RESULT-LISTE ONLY OCCURS ONCE ANYWAY
foreach( $p_html->find("table[class=result-liste] tr") as $row)
{
//grab only rows where there is a link
if( $row->find('td a') )
{
$d_price = $this->get_price($row->first_child());
$d_propid = $this->get_prop_id($row->outertext);
$data = array(
"price" => $d_price,
"prop_id" => $d_propid
);
print_r($data);
}
}
//MY ATTEMPT TO AVOID THE SECOND FOREACH DOES NOT WORK ...
$row = $p_html->find("table[class=result-liste] tr");
if( is_object($row) && $row->find('td a')) print "yes ";
else print "no ";
}
I'm using simple_html_dom_helper so do some screen scraping and am encountering some errors.
The second foreach runs 4 times (since sizeof($pages) == 4
), while it should only run once. I got this code from an example script where table.result-liste
occurs several times on the page. In my case it only occurs once, so imho there is no need for a foreach. The print_r($data)
prints out the same thing 4 times and there's no need for that.
Further down I'm trying to do the same without the foreach but it just prints out no
, so there seems to a different response and am not sure why.
foreach( $pages as $page )
{
$p = $this->create_url($codes[0], $price, $page); //pass page number along
$p_html = file_get_html($p);
$row = $p_html->find("table[class=result-liste] tr");
//RUNS OK BUT NO NEED TO DO IT FOUR TIMES.
//CLASS RESULT-LISTE ONLY OCCURS ONCE ANYWAY
foreach( $p_html->find("table[class=result-liste] tr") as $row)
{
//grab only rows where there is a link
if( $row->find('td a') )
{
$d_price = $this->get_price($row->first_child());
$d_propid = $this->get_prop_id($row->outertext);
$data = array(
"price" => $d_price,
"prop_id" => $d_propid
);
print_r($data);
}
}
//MY ATTEMPT TO AVOID THE SECOND FOREACH DOES NOT WORK ...
$row = $p_html->find("table[class=result-liste] tr");
if( is_object($row) && $row->find('td a')) print "yes ";
else print "no ";
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
尽管
table[class=result-liste]
仅在页面上出现一次,但此 find 语句正在查找作为表行的元素。因此,除非您的表格只有一行,否则您将需要这个
foreach
。Even though the
table[class=result-liste]
only occurs once on your page, this find statement is looking for the<tr>
elements that are the table's rows. So unless your table has only one row, you will need thisforeach
.您的代码
用我的代码替换上面的代码
尝试使用这个。
Your code
Replace above code by MY code
Try with this.