添加到数组时在 foreach 循环内使用条件

Using a conditional inside a foreach loop when adding to array

我无法让它正常工作。我正在使用 xpath 选择器抓取一个网站,这个 returns 38 个结果被添加到数组 $list 中。现在前 5 个结果和后 3 个对我没用。我需要的是只将结果 6-35 添加到数组中。我已经尝试了很多不同的 if、for 和 while 条件组合,但似乎无法使它起作用。我很想听听我做错了什么,并最终让它发挥作用。

$url = "www.theurl.com";
$html = new DOMDocument();
@$html->loadHtmlFile($url);
$xpath = new DOMXPath($html);

$nodelist = $xpath->query("//span[@class='mp-listing-title']");

$list = array();

$i = 0;

foreach ($nodelist as $n) {
  $i++;
}
if ($i >=5 && $i <=35) {
  $value = $n->nodeValue;
  $list[] = $value;
}

感谢您的帮助!

试试这个,它可以帮助你:

 $url = "www.theurl.com";
 $html = new DOMDocument();
 @$html->loadHtmlFile($url);
 $xpath = new DOMXPath($html);

 $nodelist = $xpath->query("//span[@class='mp-listing-title']");

 $list = array();

 $i = 0;

 foreach ($nodelist as $n) {
   if ($i >=5 && $i <=35) {
     $value = $n->nodeValue;
     $list[] = $value;
   }
   $i++;
 }

尝试以下操作:

$url = "www.theurl.com";
$html = new DOMDocument();
@$html->loadHtmlFile($url);
$xpath = new DOMXPath($html);

$nodelist = $xpath->query("//span[@class='mp-listing-title']");

$list = array();

$i = 0;

foreach ($nodelist as $n)  {
  if ($i >=5 && $i <=35) {
    $value = $n->nodeValue;
    $list[] = $value;
  }
  $i++;
}

你的条件超出了循环范围。