Monday, 27 August 2018

PHP fills a multidimensional array with data from several foreach

I am scraping an ecommerce website and need to get some data from products, like product name, price, ...
For that, I have:
...
// library includes...
$html = file_get_html($link);
foreach($html->find('.productBoxClass') as $element){

  foreach($element->find('.productTitle') as $product) {
    $product = $product->plaintext;
  }

  foreach($element->find('.price') as $price) {
    $price = $price->outertext;
  }  

   // and so on...
}

I wanna save this data in a database. So, I want to save all the data in an array for after verify each product if I have to insert or just update. I am intending to populate an multi-dimensional array with this data:
Each position of the array with another array containing the information about one product... To make it easier to save in the database after...
Any help?

This seems like an abnormal data structure or you should be looping through it differently. But if it is an abnormal structure and the product and price aren't grouped together, they are just listed in the same order, then this should work:
$products = [];

$i = 0;
foreach($element->find('.productTitle') as $product) {
   $products[$i++]['product'] = $product->plaintext;
}

$i = 0;
foreach($element->find('.price') as $price) {
   $products[$i++]['price'] = $price->outertext;
}

Note the $i++ as the key which will increment $i each loop.
If the product and pricing are grouped together in an element, then you should be looping on that element and there should be no need for a foreach for product and price.

0 comments:

Post a Comment