foreach有两个数组

时间:2018-09-22 12:45:44

标签: php arrays for-loop foreach

我有问题,我需要foreach两个数组才能从两个jsons信息获取到一个foreach。现在代码看起来像

foreach($videoList->items as $item){

但是我需要两个这样的数组

foreach($videoList->items as $item) and ($videoViews->items as $items){

代码:

foreach($videoList->items as $item){    
        if(isset($item->id->videoId) && ($items->statistics->viewCount)){
            echo '<div class="video">           
                    <iframe width="280" height="150" src="https://www.youtube.com/embed/'.$item->id->videoId.'" frameborder="0" allowfullscreen></iframe>
                    <h5>'. $item->snippet->title .'</h5>
                    <h5>'.$items->statistics->viewCount.' &nbsp; '.$items->statistics->likeCount.' &nbsp; '.$items->statistics->dislikeCount.'</h5>
                </div>';
        }

    }

1 个答案:

答案 0 :(得分:0)

我假设$videoList$videoViews具有通用密钥,在这种情况下,您可以将循环重写为

foreach($videoList->items as $key => $item) {    
    if(isset($item->id->videoId) && ($videoViews->{$key}->statistics->viewCount)) {
        echo '<div class="video">           
              <iframe width="280" height="150" src="https://www.youtube.com/embed/'.$item->id->videoId.'" frameborder="0" allowfullscreen></iframe>
              <h5>'. $item->snippet->title .'</h5>
              <h5>'.$videoViews->{$key}->statistics->viewCount.' &nbsp; ' . 
                    $videoViews->{$key}->statistics->likeCount.' &nbsp; ' . 
                    $videoViews->{$key}->statistics->dislikeCount.'</h5>
              </div>';
    }
}