[英]PHP populate multi-dimensional array with data from many foreach
我正在抓捕一个电子商务网站,需要从产品中获取一些数据,例如产品名称,价格,...
为此,我有:
...
// 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...
}
我想将这些数据保存在数据库中。 因此,我想将所有数据保存在一个数组中,以便在验证每个产品后是否必须插入或仅更新它们。 我打算用此数据填充多维数组:
数组的每个位置与另一个数组有关,该数组包含有关一个产品的信息...为了更容易地在之后保存在数据库中,...
有什么帮助吗?
这似乎是异常的数据结构,或者您应该以不同的方式遍历它。 但是,如果结构是异常的,并且产品和价格没有组合在一起,那么它们会以相同的顺序列出,那么这应该可以工作:
$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;
}
注意$ i ++作为键,它将在每个循环中递增$ i。
如果将产品和价格分组在一个元素中,那么您应该在该元素上循环,并且不需要对产品和价格进行foreach。
请检查以下代码,让我知道您的想法...
<?php
// library includes...
$html = file_get_html($link);
$productArr = array();
foreach($html->find('.productBoxClass') as $element){
$tempArr = array('title' => '','price' => 0,'other' => ''); // declare temp array for stroing each product nodes
foreach($element->find('.productTitle') as $product) {
$tempArr['title'] = $product->plaintext; // To do check for empty text here
}
foreach($element->find('.price') as $price) {
$tempArr['price'] = $price->outertext; // To do validate the price
}
foreach($element->find('.other-features') as $price) {
$tempArr['other'] = $price->outertext; // To do validate the price
}
// and so on... with $tempArr['key']
// then assign
$productArr[] = $tempArr; // save temp array in global product array
}
// Product array
echo '<pre>';print_r($productArr);die;
首先用于每个计数项目:
...
// library includes...
$html = file_get_html($link);
// Array declaration
$products = array();
foreach($html->find('.productBoxClass') as $i => $element){
foreach($element->find('.productTitle') as $product) {
$products[$i]['name'] = $product->plaintext;
}
foreach($element->find('.price') as $price) {
$products[$i]['price'] = $price->outertext;
}
// and so on...
}
并会导致:
Array
(
[0] => Array
(
[name] => Product 1
[price] => 1.00
)
[1] => Array
(
[name] => Product 1
[price] => 1.00
),
...
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.