如果条件满足,则将元素分配给for-each循环中的数组

时间:2014-05-02 05:40:31

标签: php foreach simple-html-dom

这里是我的代码

$url = 'link.html'

$html = file_get_html($url);

$dayArray = array('28th Apr 2014', '29th Apr 2014' , '30th Apr 2014' ,'1st May 2014');

foreach($dayArray as $value){ 

$dayArrayvalue=strtotime($value);
$month_name=date("F",$dayArrayvalue);


foreach($html->find('table',1)->find('a') as $elm) {

if($elm->plaintext == $month_name){
    $month_links1= $elm->href;

//array_push($month_links, $month_links1);

$month_links[] = $month_links1;

}
else{
  $month_links[] = 0;
}

}
}

print_r( $month_links);

如果月份名称与月份日期匹配,我想在aaray中存储每个月的链接

在link.html中,第二个表包含带链接的月份

任何人都可以帮助我吗?

1 个答案:

答案 0 :(得分:0)

试试这个更新版本,我猜你想要什么,因为你没有清楚地解释你的代码背后的目标是什么。

$url = 'link.html'
$html = file_get_html($url);
//$dayArray = array('28th Apr 2014', '29th Apr 2014' , '30th Apr 2014' ,'1st May 2014');
$monthNameArray = array('April', 'May');
$month_links = array();

foreach($monthNameArray as $month_name){ 

    //$dayArrayvalue=strtotime($value);
    //$month_name=date("F",$dayArrayvalue);

    foreach($html->find('table',1)->find('a') as $elm) {

        if(strcasecmp($elm->plaintext,$month_name)==0){
            array_push($month_links, $elm->href);
        }
        //else{
        //this will add a 0 to the array if there is no match. I don't think this is what you want, so just remove it if not needed
       //      array_push($month_links, '0');
       // }
    }
}

print_r( $month_links);