Search code examples
phpforeachimplode

Implode one array then move onto the next array


Having a little problem with imploding a number of arrays within a foreach loop.

The arrays look like this at the moment.

Array (
[0] => Array ( [img] => /Content/ProductImages/big/9414339613250.jpg [prodtitle] => Heineken Lager 330ml Btls [unit] => 12pk [price] => [wasprice] => 26.99 [specprice] =>      ) 
[1] => Array ( [img] => /Content/ProductImages/big/7501064191367.jpg [prodtitle] => Corona Extra Beer 355ml Bottles [unit] => 12pk [price] => [wasprice] => 26.99 [specprice] => 22.99 )     
[2] => Array ( [img] => /Content/ProductImages/big/9414774095307.jpg [prodtitle] => Steinlager Lager 330ml Btls [unit] => 12pk [price] => [wasprice] => 23.99 [specprice] => 21.99 )

However within the foreach loop it only implodes the 1st array the number of times the loop has to go on for:

/Content/ProductImages/big/9414339613250.jpg','Heineken Lager 330ml Btls ','12pk ','','26.99','20.99
/Content/ProductImages/big/9414339613250.jpg','Heineken Lager 330ml Btls ','12pk ','','26.99','20.99
/Content/ProductImages/big/9414339613250.jpg','Heineken Lager 330ml Btls ','12pk ','','26.99','20.99

I want it to move through each of the arrays. The number or arrays is not specific as items maybe added or subtracted.

/Content/ProductImages/big/9414339613250.jpg','Heineken Lager 330ml Btls ','12pk','','26.99','20.99
/Content/ProductImages/big/7501064191367.jpg','Corona Extra Beer 355ml Bottles ','12pk ','','26.99','22.99

The entire code looks like this:

$html = file_get_html($url);

foreach($html->find('div.product-details-contents') as $content) {
    $detail['img'] = $content->find('img.product-details-image',0)->src;
    $detail['prodtitle'] = $content->find('span.title', 0)->plaintext;
    $detail['unit'] = $content->find('span.unit-size', 0)->plaintext;
    $detail['price'] = filter_var($content->find('span.price', 0)->plaintext, FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION | FILTER_FLAG_ALLOW_THOUSAND);
    $detail['wasprice'] = filter_var($content->find('span.was-price', 0)->plaintext, FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION | FILTER_FLAG_ALLOW_THOUSAND);
    $detail['specprice'] = filter_var($content->find('span.special-price', 0)->plaintext, FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION | FILTER_FLAG_ALLOW_THOUSAND);

    $product[] = $detail;

    $sqlstring = implode("','", $product[0]);
    echo $sqlstring;
}
print_r($product);

Also when $sqlstring = implode("','", $product[0]); $product[0] is increased in number, it give errors such as:

Warning: implode() [function.implode]: Invalid arguments passed.


Solution

  • You say that only the first array is being imploded. Well, as it seems:

    $sqlstring = implode("','", $product[0]);
    

    This peace of codes always implodes the first element of the product array. Why not doing smth like:

    $sqlstring = implode("','", $detail);