删除路径中带点的元素不起作用

时间:2017-04-19 15:47:43

标签: php arrays

我需要删除包含数组中包含dot的所有元素,我接收到了ftp_nlist(),这就是我这样做的方法:

$connection = ftp_connect($host);
if(!$connection){
    echo "Can't connect to $host ($login:$password)\n";
    #print_r(error_get_last());

    ftp_close($connection);
    exit();
}
ftp_login($connection, $login, $password);
ftp_pasv($connection, TRUE); 
$files_list = ftp_nlist($connection, $path);
print_r($files_list);
for($i = 0; $i< count($files_list); $i++){
    if( strstr($files_list[$i], '.') ){
        unset($files_list[$i]);

    }
}
print_r($files_list);
echo 'Ok';

然而它很奇怪

Array
(
    [0] => /httpdocs/favicon.ico
    [1] => /httpdocs/mobile.html
    [2] => /httpdocs/g
    [3] => /httpdocs/index.html
    [4] => /httpdocs/.
    [5] => /httpdocs/member.html
    [6] => /httpdocs/sitemap.xml
    [7] => /httpdocs/animated_favicon1.gif
    [8] => /httpdocs/rakuten.html
    [9] => /httpdocs/y_key_8866d9fb86f18b30.html
    [10] => /httpdocs/robots.txt
    [11] => /httpdocs/..
    [12] => /httpdocs/bbs.html
    [13] => /httpdocs/version.php
    [14] => /httpdocs/css
    [15] => /httpdocs/nas
    [16] => /httpdocs/googlee7e5921970ceb672.html
    [17] => /httpdocs/about.html
    [18] => /httpdocs/images
)
Array
(
    [2] => /httpdocs/g
    [10] => /httpdocs/robots.txt
    [11] => /httpdocs/..
    [12] => /httpdocs/bbs.html
    [13] => /httpdocs/version.php
    [14] => /httpdocs/css
    [15] => /httpdocs/nas
    [16] => /httpdocs/googlee7e5921970ceb672.html
    [17] => /httpdocs/about.html
    [18] => /httpdocs/images
)
Ok

正如您所看到的,并非所有带点的元素都被删除了。我无法清楚地知道原因。

1 个答案:

答案 0 :(得分:2)

每当你unset()数组元素时,条件中的count()减少1.因此,不是在条件中使用count($files_list);(这是每次迭代计算),设置它首先,它不会改变:

$count = count($files_list);

for($i = 0; $i < $count; $i++){
    if(strpos($files_list[$i], '.') !== false){
        unset($files_list[$i]);    
    }
}

我更希望foreach()

foreach($files_list as $key => $file){
    if(strpos($file, '.') !== false){
        unset($files_list[$key]);    
    }
}

另请注意strpos()更适合此处。