php - Adding to array from multiple foreach statements -
i'm trying add dynamically generated variables $title
, $price
array $list
.
this works degree. code creates array keys have title , price value.
the price value correct , different each key. however, seems first title
result added, creating following array (same title untill key 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 " }
looking @ code think because first foreach loop executing second one.
i know correct values $title
there, because when isolate title foreach loop this:
foreach ($titlehit $titles) { $title = $titles->nodevalue; echo "$title"; }
30 different $title
result displayed
$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 $titles) { foreach ($pricehit $prices) { if ($i >=5 && $i <=35) { $title = $titles->nodevalue; $price = $prices->nodevalue; $list[] = array( 'title' => $title, 'price' => $price ); } $i++; } }
how can array $list
hold both correct title , price values? help.
assuming each title, there 1 price i.e there 1:1 title-to-price ratio in corresponding arrays, need 1 loop.
$list = array(); $i = 0; // initialize // assuming $titlehit , $pricehit have same number of elements foreach ($titlehit $titles) { // assuming $pricehit simple array. if associative array, need use corresponding key index instead of $i. we'll once can confirm input. $prices = $pricehit[$i]; // not entirely sure why need condition. if ($i >=5 && $i <=35) { $title = $titles->nodevalue; $price = $prices->nodevalue; $list[] = array( 'title' => $title, 'price' => $price ); } $i++; }
Comments
Post a Comment