【问题标题】:How to use two foreach and if else in PHP如何在 PHP 中使用两个 foreach 和 if else
【发布时间】:2020-07-16 14:19:31
【问题描述】:

我想检查某些 URL 中是否存在某些文件。 这里的两个数组是独立的。首先,我想检查 url1 中 $files 数组中的每个文件是否存在。如果 url1 中存在文件/文件,则回显“找到这些文件”。如果没有,请检查url2中是否存在文件等。

如果任何 url 中都不存在任何文件,则回显“未找到文件”。

我已经编写了一些代码,现在我需要你的帮助。

$urls  = array('url1','url2','url3');

$files = array('file1','file2','file3');

foreach ($urls as $url) & foreach($files as $file)
{
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_NOBODY, true);
curl_exec($ch);
$retcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

    if($retcode==200)
    {
    echo "found these files";
    }else{
    "no file found"
    }
}

【问题讨论】:

  • 您只提供了伪代码。您是否实际尝试过找到解决方案?
  • 如果它在异地,你需要做一个HEAD request,如果不是那么就使用 file_exists
  • 嗨,我已经更新了代码。

标签: php if-statement foreach


【解决方案1】:
    $urls  = array('url1','url2','url3');
    $files =  array('url1','url2','url3');

    foreach ($files as $key => $single_file)
    {
        if(in_array($single_file, $urls))
        {
            echo "found these files";
        }else{
            echo "no file found";
        }
    }

【讨论】:

    【解决方案2】:

    我发现以下代码很有帮助。

    <?
    $urls  = array('url1','url2','url3');
    
    $files = array('file1','file2','file3');
    foreach ($urls as $url)
    {
        foreach ($files as $fil)
        {
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_NOBODY, true);
    curl_exec($ch);
    $retcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    
        if($retcode==200)
        {
        echo "found these files";
        }else{
        echo "no file found";
        }
    }
    }
    ?>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-11-13
      • 2022-01-25
      • 1970-01-01
      • 1970-01-01
      • 2021-10-05
      • 2012-09-02
      • 1970-01-01
      • 2016-08-16
      相关资源
      最近更新 更多