PHP使用来自多个foreach的数据填充多维数组
我正在抓取一个电子商务网站,需要从产品中获取一些数据,如产品名称、价格等 为此,我:PHP使用来自多个foreach的数据填充多维数组,php,arrays,multidimensional-array,Php,Arrays,Multidimensional Array,我正在抓取一个电子商务网站,需要从产品中获取一些数据,如产品名称、价格等 为此,我: ... // library includes... $html = file_get_html($link); foreach($html->find('.productBoxClass') as $element){ foreach($element->find('.productTitle') as $product) { $product = $product->pla
...
// 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;
在第一个foreach中使用计数项:
Array
(
[0] => Array
(
[name] => Product 1
[price] => 1.00
)
[1] => Array
(
[name] => Product 1
[price] => 1.00
),
...
)
这将导致:
使用您的语句foreach($element->find('.productTitle')作为$product).
,$product是一个带有数据副本的变量。用$product->plaintext
替换它是有道理的,但是,从目前的情况来看,它似乎是在丢弃结果-它没有被分配到任何地方。这是你的意图吗?很好!但这只是第一个产品。当我打印数组时,数组只有一个位置,里面有一个产品……问题是,通过运行foreach($element->find('.productTitle'))
我假设可以有多个位置,并且您的代码只会覆盖每个位置。
Array
(
[0] => Array
(
[name] => Product 1
[price] => 1.00
)
[1] => Array
(
[name] => Product 1
[price] => 1.00
),
...
)