【问题标题】:Combine elements of one foreach into another将一个 foreach 的元素组合成另一个
【发布时间】:2014-07-16 02:24:25
【问题描述】:

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

....等

【问题讨论】:

    标签: php arrays foreach simple-html-dom


    【解决方案1】:

    我通过向 foreach 添加索引键解决了这个问题。喜欢:

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

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

    【讨论】:

      猜你喜欢
      • 2017-03-23
      • 2023-01-18
      • 1970-01-01
      • 2018-02-17
      • 2017-03-23
      • 1970-01-01
      • 1970-01-01
      • 2021-08-02
      • 2015-08-15
      相关资源
      最近更新 更多