将一个foreach的元素组合到另一个foreach中

时间:2014-07-16 02:24:25

标签: php arrays foreach simple-html-dom

我有两个foreach循环,我希望匹配第一个和第二个的输出。第一个从起始页面获取标题,而第二个foreach导航到子页面以获取描述。我似乎无法将两个内联输出,以便标题与相关描述一起显示。

//1st foreach:

$title = array();
foreach ($html->find('.event-box .event-details h1') as $t){
        $title[] = $t->plaintext;
    }
    echo implode('<br>',$title);'<br>';
 //this lists all $title found on page ahead of the below foreach (obvisouly)

//2nd foreach:

    // loop through each link
foreach ($anchors as $anchor) {
    // Create the new link to follow and parse
    $urlTemp = $baseUrl . $anchor->href;
    $html2 = new simple_html_dom();
    $html2->load_file($urlTemp);

    //Descriptions
    foreach($html2->find('div[id=content-area]') as $article) {
    }   $para = array();
        foreach($article->find('p') as $p) {
                $para[] = $p->innertext;    }


    echo 'DESC: '.implode('<br>',$para);'<br>';
    echo "<hr/>";

    $html2->clear(); 
    unset($htm2);
}

我希望按此顺序获取输出,以便$title跟随每个迭代的$para$title需要与$para

匹配
$title //From first foreach - 1st in $title[]
$para //From second foreach - 1st in $para[]
</hr>
$title //From first foreach - 2nd in $title[]
$para //From second foreach - 2nd in $para[]
</hr>
$title
$para

....等

1 个答案:

答案 0 :(得分:0)

我通过向foreach添加索引键来解决这个问题。像:

    $i=0;

    foreach ($anchors as $key=>$anchor) { 
    //...........
    echo 'TITLE: '.$title[$i].'<br>';
    //...........
    $i++;

第一个foreach中的数组元素与第二个$title[1], $title[2]等的索引键匹配的内容可以通过$title[$i]实现