2017-07-25 97 views
0

我试图将动态生成的变量$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保存正确的标题和价格值?谢谢你的帮助。这里

+0

'$ i'用于什么?作为柜台? – MaxZoom

+0

$ i被用作计数器,只将结果5-> 35添加到数组中。之前的代码返回更多结果。 – Peter

+0

@Peter如果只有30个标题,为什么你使用魔法数字35?不知道为什么你需要从第5位开始。 – MaxZoom

回答

0

假设为每个标题,有一个价格,即在相应的数组中存在1:1的标题 - 价格比率,您只需要1个循环。

$list = array(); 
$i = 0; // initialize 
// Assuming $titlehit AND $pricehit have the same number of elements 
foreach ($titlehit as $titles) { 
    // Assuming $pricehit is a simple array. If it is an associative array, we need to use the corresponding key as the index instead of $i. We'll get to this once you can confirm the input. 
    $prices = $pricehit[$i]; 
    // Not entirely sure why you need this condition. 
    if ($i >=5 && $i <=35) { 
     $title = $titles->nodeValue; 
     $price = $prices->nodeValue; 
     $list[] = array(
      'title' => $title, 
      'price' => $price 
     ); 
    } 
    $i++; 
} 
+1

谢谢,这个作品。 $ i用作计数器以确保只有结果5 - > 35来自前面的代码才会被添加到数组中。 – Peter

0

不完全是足够的代码肯定知道,但它看起来像你需要你的迭代$iforeach循环的每个迭代复位:

$list = array();  
    foreach ($titlehit as $titles) { 
    $i = 0; 
    foreach ($pricehit as $prices) { 
     if ($i >=5 && $i <=35) { 
     $title = $titles->nodeValue; 
     $price = $prices->nodeValue; 
     $list[] = array(
      'title' => $title, 
      'price' => $price 
     ); 
     } 
     $i++; 
    } 
    }