在循环内合并数据

时间:2017-11-21 20:57:05

标签: php dom

我尝试使用DimDom(https://github.com/cevin/DiDOM)开发报废价格(就像简单的HTML Dom一样) 我的问题是在同一个数组中包含2个元素:标题和价格

谢谢。

在那里,我的功能没有完成,因为我找不到解决方案。

    public function getProductListingPrice($url) {

          $html = $this->getHTML($url); // result of curl
          $element = $this->document->loadHtml($html); // include html content

          $content = $element->first('div.lpTopBox'); // content of the div

          $price = $content->find('span.price'); // price content inside the div
          $title = $content->find('div.prdtBTit'); // title inside the div

          $i = 0;

          foreach($price as $value) {
            $product_price[$i] = $value->text();
            $price_result[] = $product_price[$i];
            $i = $i+1;
          }

          foreach($title as $value) {
            $product_title[$i] = $value->text();
            $title_result[] = $product_title[$i];
            $i = $i+1;
          }

var_dump($title_result);
var_dump($price_result);

          return $result;
    }

结果是:

array (size=5)
  0 => string 'LG 55EG9A7V TV OLED FULL HD 139 cm (55") - SMART T' (length=50)
  1 => string 'LG 55UJ630V TV LED 4K HDR 138 cm (55") - Smart TV ' (length=50)
  2 => string 'SAMSUNG UE58KU6000 TV LED UHD 147 cm (58") - Smart' (length=50)
  3 => string 'LG 65UJ630V TV LED 4K HDR 164 cm (65") - Smart TV ' (length=50)
  4 => string 'LG 55UJ651V TV LED 4K HDR 139 cm (55") - Smart TV ' (length=50)

array (size=5)
  0 => string '1499€00' (length=9)
  1 => string '689€99' (length=8)
  2 => string '729€99' (length=8)
  3 => string '1141€00' (length=9)
  4 => string '749€99' (length=8)

1 个答案:

答案 0 :(得分:0)

摆脱你的foreach循环,然后你可以这样做:

function combineResult($title, $price)
{
    return(array('title' => $title->text(), 'price' => $price->text()));
}
$result = array_map("combineResult", $title, $price);
print_r($result);