【问题标题】:PHP check if file exists from arrayPHP检查文件是否存在于数组中
【发布时间】:2014-05-03 09:41:03
【问题描述】:

我有一个查询,它根据 Order_ID 从数据库中获取一些文件名。许多文件可能与一个订单相关联。查询看起来像

$download2 = xtc_db_query("SELECT orders_products_filename FROM orders_products_download WHERE orders_id='".$last_order."'");
while ($activated2 = xtc_db_fetch_array($download2)) 
{

    $file = $activated2['orders_products_filename'];
    $pieces = explode(".zip", $file);
    print_r ($pieces);

    if(file_exists($pieces.'.zip'))
    { echo "1"; }
    if(!file_exists($pieces.'.zip'))
    { echo "2"; }

}

如果文件存在与否,我想要做的是触发一个动作。由于$pieces 是一个数组file_exists 假设整个数组是一个文件并且它不起作用(它总是回显2)。如果有人能提示我如何解决这个问题,那就太好了。

【问题讨论】:

  • 你能var_dump($pieces) 吗?它是否只包含一个文件,而不是您可以通过$pieces[0] 访问它,否则您将需要一个循环。
  • explode 将在带有索引的数组中包含数据,因此在 file_exists() 中传递数组将不起作用,您需要传递数组元素而不是整个数组。

标签: php arrays file file-exists


【解决方案1】:

我认为你在追求类似的东西:

foreach ($pieces as $piece) {
    if (file_exists($piece . '.zip')) {
        echo '1';
    } else {
        echo '2';
    }
}

或者也许对数组运行一个过滤器,以获取存在的文件列表,例如:

$existingFiles = array_filter(
    $pieces,
    function ($piece) { return file_exists($piece . '.zip'); }
);

【讨论】:

    【解决方案2】:

    file_exists(); 需要绝对路径,请确保您传递的是绝对路径。

    关于代码,我建议进行一些改进,尽管这与您提出的问题无关。

    if(file_exists($pieces.'.zip')) { 
        echo "1"; 
    }
    if(!file_exists($pieces.'.zip')) { 
        echo "2"; 
    }
    

    你可以写成

    if(file_exists($pieces.'.zip')) { 
        echo "1"; 
    } else { 
        echo "2"; 
    }
    

    file_exists 不需要调用 2 次。

    如果您的意图是返回整数值,那么您可以尝试三元运算符。

    echo file_exists($pieces.'.zip') ? 1 : 2;
    

    【讨论】:

      猜你喜欢
      • 2011-05-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-01
      • 2023-01-02
      • 1970-01-01
      • 2016-06-22
      相关资源
      最近更新 更多