简体   繁体   English

嵌套的foreach循环

[英]Nested foreach loops

I know this solution is simple, but it keeps slipping my mind. 我知道这个解决方案很简单,但是却让我无所适从。 When I parse the page with this code and the $links array is printed, all of href parts are correct yet the img part only prints the last src element that is found on the page. 当我使用此代码解析页面并打印$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));

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

You use the dublicate variable $item in internal foreach. 您可以在内部foreach中使用双变量$item

Try this without internal foreach 尝试此操作而无需内部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));

Check if this works for you: 检查是否适合您:

$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));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM