1

不能让它工作!啊。现在,如果我从 /uploads 中删除 test.rar,我想从中删除它,$row['attachments']但它不会!有一段时间一直在挠头...

我在这里做错了什么?

$row['attachments'] = "angeleyes.jpg|test.rar"; // in reality i get this from the database
$attachments = explode('|', $row['attachments']);
$dir = "../uploads/";

if ($row['attachments']) {

    foreach($attachments as $file) {

        if(is_file($dir.$file))
            echo '<a href="#">'.$file.'</a> ('.filesize_formatted($dir.$file).') <br>';

        // If file wasnt found, clean up
        else {

            // Remove it
            $list_of_attachments = $row['attachments'] ? explode("|", $row['attachments']) : array();
            if(!in_array($file, $list_of_attachments)) $list_of_attachments[] = $file;
            $newstring = implode("|", $list_of_attachments);

            // lets see if it works
            var_dump($newstring);

             // update db
        }
    }

}
4

3 回答 3

0

!in_array($file, $list_of_attachments)测试总是错误的(因为$file从迭代一个总是等于 的数组中获取$list_of_attachments)不管怎样,最严重的问题是你永远不会删除实际的数组元素!声称删除文件的行实际上并没有,因为它们没有采取任何步骤从数组中删除元素,或者在没有它的情况下创建一个新数组。

更不用说您当前的实现$row['attachments']在迭代时必须覆盖它,这不是一个好主意。

于 2013-06-08T10:34:16.593 回答
0

在你的else声明中:

$list_of_attachments = $row['attachments'] ? explode("|", $row['attachments']) : array();

首先,您已经在$attachments中分解了 $row['attachments']

其次,只有在上述条件下才能达到代码:

if ($row['attachments']) 

所以这条线看起来没用。你打算用它做什么?

然后 :

if(!in_array($file, $list_of_attachments)) $list_of_attachments[] = $file;

如果$file在您的硬盘上不存在但仍存在于 *$list_of_attachments* 中(该数组是$attachments ... 的副本),则将其添加到 *$list_of_attachments*。据我所知,您永远不会删除它...

如果你想删除它,清理你的代码,可以尝试这样的事情:

// $row['attachments'] = "angeleyes.jpg|test.rar";
$attachments = explode('|', $row['attachments']);
$dir = "../uploads/";
$remove = array();
foreach ($attachments as $file) {
    if (is_file($dir . $file)) {
        /**
         * File exists : print
         */
        echo '<a href="#">' . $file . '</a> (' . filesize_formatted($dir . $file) . ') <br>';
    }
    else {
        /**
         * File does not exists : remove it from $attachments
         */
        $remove[] = $file;
    }
}
$attachments = array_diff($attachments, $remove);
// then update whatever...

[注意:未经测试的代码...不要盲目复制/粘贴...]

于 2013-06-08T10:40:58.917 回答
0

尝试这样的事情:(
另请参阅这个简短的演示。)

$row["attachments"] = "angeleyes.jpg|test.rar";
$attachments = explode("|", $row["attachments"]);
$newAttachments = array();
$dir = "../uploads/";

if ($row["attachments"]) {
    forEach ($attachments as $file) {
        if (is_file($dir . $file)) {
            echo('<a href="#">' . $file . '</a> ('
                 . filesize_formatted($dir . $file) . ') <br>');
            $newAttachments[] = $file;
        }
    }

    $newAttachments = implode("|", $newAttachments);
    if (strCaseCmp($row["attachments"], $newAttachments) != 0) {
        echo("You need to update the DB:");
        var_dump($newAttachments);
    } else {
        echo("No need to update !");
    }
}
于 2013-06-08T10:42:28.867 回答