我试图将动态生成的变量$title
和$price
添加到数组$list
。从多个foreach语句添加到数组
这在一定程度上起作用。该代码使用具有标题和价格值的键创建一个数组。
价格值是正确的,每个键都不同。然而,似乎只有第一title
结果被添加,创建下列阵列(相同的标题,直到键30)
[0]=> array(2) { ["title"]=> string(57) "Gibson Les Paul ** Nr.1 Gibson dealer ** 18 gitaarwinkels" ["price"]=> string(25) " € 300,00 " } [1]=> array(2) { ["title"]=> string(57) "Gibson Les Paul ** Nr.1 Gibson dealer ** 18 gitaarwinkels" ["price"]=> string(25) " € 100,00 " }
看代码,我认为这是因为第一个foreach循环仅执行第二个。
我知道$title
正确的价值观在那里,因为当我分离标题foreach循环是这样的:
foreach ($titlehit as $titles) {
$title = $titles->nodeValue;
echo "$title";
}
30个不同的显示$title
结果
$url = "https://url.com";
$html = new DOMDocument();
@$html->loadHtmlFile($url);
$xpath = new DOMXPath($html);
$titlehit = $xpath->query("//span[@class='mp-listing-title']");
$pricehit = $xpath->query("//span[@class='price-new']");
$list = array();
$i = 0;
foreach ($titlehit as $titles) {
foreach ($pricehit as $prices) {
if ($i >=5 && $i <=35) {
$title = $titles->nodeValue;
$price = $prices->nodeValue;
$list[] = array(
'title' => $title,
'price' => $price
);
}
$i++;
}
}
我怎样才能得到数组$list
保存正确的标题和价格值?谢谢你的帮助。这里
'$ i'用于什么?作为柜台? – MaxZoom
$ i被用作计数器,只将结果5-> 35添加到数组中。之前的代码返回更多结果。 – Peter
@Peter如果只有30个标题,为什么你使用魔法数字35?不知道为什么你需要从第5位开始。 – MaxZoom