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


Combine elements of one foreach into another

我有两个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

…等

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

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

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