PHP 检查数组中文件是否存在

use*_*959 1 php arrays file file-exists

我有一个查询,它根据 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"; }

}
Run Code Online (Sandbox Code Playgroud)

我想要做的是如果文件存在或不存在则触发一个操作。As $piecesis an arrayfile_exists假设整个数组是一个文件,并且它不起作用(它总是回显 2)。如果有人给我提示如何解决这个问题,那就太好了。

Phy*_*sis 5

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

foreach ($pieces as $piece) {
    if (file_exists($piece . '.zip')) {
        echo '1';
    } else {
        echo '2';
    }
}
Run Code Online (Sandbox Code Playgroud)

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

$existingFiles = array_filter(
    $pieces,
    function ($piece) { return file_exists($piece . '.zip'); }
);
Run Code Online (Sandbox Code Playgroud)