爆炸和崩溃

时间:2013-06-08 10:27:52

标签: php

无法让这个工作!哎呀。现在,如果我从/ 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
        }
    }

}

3 个答案:

答案 0 :(得分:0)

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

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

答案 1 :(得分: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...

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

答案 2 :(得分:0)

尝试这样的事情:
(另请参阅此 short demo 。)

$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 !");
    }
}