如果elseif条件在foreach内部有数组

时间:2016-10-18 12:05:13

标签: php arrays function if-statement foreach

我在foreach循环中使用if elseif条件。在ifelseif内部,两个不同的函数正在调用并检索相同数组$nice[]的值。如果我运行以下代码,则只有if条件正在运行。

$youtube = array(
             'https://www.youtube.com/watch?v=nCwRJUg3tcQ1&list=PLv5BUbwWA5RYaM6E-QiE8WxoKwyBnozV2&index=4',
             'http://vimeo.com/channels/vimeogirls/87973054123',
             'http://www.youtube.com/watch?v=nCwRJUg3tcQ2&feature=relate',
             'http://youtube.com/v/nCwRJUg3tcQ3?feature=youtube_gdata_player');  

$nice = array();  

foreach ($youtube as $url) {
    if(preg_grep("/youtu/i", $youtube)){
        $nice[] = getYoutubeId($url);
    }elseif(preg_grep("/vimeo/i", $youtube)){
        $nice[] = getVimeoId($url);
    }
}  

print_r($nice);  

function getVimeoId($url)
{
    if (preg_match('#(?:https?://)?(?:www.)?(?:player.)?vimeo.com/(?:[a-z]*/)*([0-9]{6,11})[?]?.*#', $url, $m)) {
        return 'v_'.$m[1];
    }
    return false;
}  

function getYoutubeId($url)
{
    $parts = parse_url($url);
    if (isset($parts['host'])) {
        $host = $parts['host'];
        if (false === strpos($host, 'youtube') &&
            false === strpos($host, 'youtu.be')
            ) 
        {
            return false;
        }
    }
    if (isset($parts['query'])) {
        parse_str($parts['query'], $qs);
        if (isset($qs['v'])) {
            return 'y_'.$qs['v'];
        }
        else if (isset($qs['vi'])) {
            return 'y_'.$qs['vi'];
        }
    }
    if (isset($parts['path'])) {
        $path = explode('/', trim($parts['path'], '/'));
        return 'y_'.$path[count($path) - 1];
    }
    return false;
}

目前的输出是:

    Array ( 
        [0] => y_nCwRJUg3tcQ1 
        [1] => 
        [2] => y_nCwRJUg3tcQ2 
        [3] => y_nCwRJUg3tcQ3 
    )  

[1]位置没有价值。

1 个答案:

答案 0 :(得分:-1)

  

首先,您的if()条款正在检查主阵列$youtube而不是值$url
或许,下面的代码段有助于:

    $youtube = array(
        'https://www.youtube.com/watch?v=nCwRJUg3tcQ1&list=PLv5BUbwWA5RYaM6E-QiE8WxoKwyBnozV2&index=4',
        'http://vimeo.com/channels/vimeogirls/87973054123',
        'http://www.youtube.com/watch?v=nCwRJUg3tcQ2&feature=relate',
        'http://youtube.com/v/nCwRJUg3tcQ3?feature=youtube_gdata_player');

    $nice = array();

    foreach ($youtube as $url) {
        if(preg_match("#youtu#i", $url)){
            $nice[] = getYoutubeId($url);
        }elseif(preg_match("#vimeo#i", $url)){
            $nice[] = getVimeoId($url);
        }
    }