嵌套的foreach循环

时间:2015-12-04 05:29:48

标签: php

我知道这个解决方案很简单,但它一直让我不知所措。当我使用此代码解析页面并打印$links数组时,所有href部分都正确但img部分仅打印找到的最后src个元素在页面上。

$doc = new DOMDocument();
$doc->loadHTML($html);
$links = array();
$images = $doc->getElementsByTagName("img");
$arr = $doc->getElementsByTagName("a");

    foreach($arr as $item) {
        // get links
        $href =  $item->getAttribute("href");

        // get images.
        foreach ($images as $item) {
            $img = $item->getAttribute('src');
        }    

        $links[] = array(
            'href' => $href,
            'img' => $img
        );
    }

print_r(array_values($links));

3 个答案:

答案 0 :(得分:0)

对于图像的每个语句应该构建一个数组,其中最终数组($ links)是一个多维数组($ img是嵌套数组)。

答案 1 :(得分:0)

您在内部foreach中使用dublicate变量$item

在没有内部foreach

的情况下尝试此操作
$doc = new DOMDocument();
$doc->loadHTML($html);
$links = array();
$images = $doc->getElementsByTagName("img");
$arr = $doc->getElementsByTagName("a");

    foreach($arr as $key=>$item) {
        // get links
        $href =  $item->getAttribute("href");

        $img = $images[$key]->getAttribute('src');

        $links[] = array(
            'href' => $href,
            'img' => $img
        );
    }unset($item);

print_r(array_values($links));

答案 2 :(得分:0)

检查这是否适合您:

$doc = new DOMDocument();
$doc->loadHTML($html);
$links = array();
$images = $doc->getElementsByTagName("img");
$arr = $doc->getElementsByTagName("a");

foreach($arr as $item) {
    // get links
    $href =  $item->getAttribute("href");

    // get images.
    foreach ($images as $item) {
        $img = $item->getAttribute('src');

        // storing the image src 
        $links[] = array(
           'img' => $img
        );
    }    

    $links[] = array(
        'href' => $href
    );
}

print_r(array_values($links));
相关问题