来自if(){...}条件的elseif(){..}条件中的Acess数组数据

时间:2016-03-30 16:07:35

标签: php arrays forms form-submit

我在一个表单中有两个表单提交按钮,我想在$uploaded elseif() {...}中使用$data ['pic_path'] = $uploaded;数组,但它不起作用。我只能在$uploaded内或html内部打印出if () {...}。我该怎么做才能将$uploaded保存在$data数组中?谢谢!

以下是代码:

<?php
if (isset($_POST[submit_image])) {
    if (!empty($_FILES["files"]["name"][0])) {
        $files = $_FILES["files"];
        //arrarys to include files uploaded successfully and failed
        $uploaded = array();
        $failed = array();
        //access tmp_name arrary
        foreach ($files['name'] as $position => $file_name) {
            $file_tmp = $files["tmp_name"][$position];

            $file_ext = explode(".", $file_name);
            $file_ext = strtolower(end($file_ext));

            $file_name_new = uniqid("", true) . "." . $file_ext;
            $file_destination = "uploads/" . $file_name_new;
            if (move_uploaded_file($file_tmp, $file_destination)) {
                $uploaded[$position] = $file_destination;
            } else {
                $failed[$position] = "error";
            }   
        } 
        print_r($uploaded);
    }
} elseif (isset($_POST[submit_post])) {
        $data = array();
        $data['comments'] =  $_POST['comments'];
        //$data ['pic_path'] = $uploaded;
        //print_r($uploaded);
}   
?>

<!DOCTYPE html>
    <head>        
    </head>
    <body>
        <form method="post" enctype="multipart/form-data">
            <input type="file" name="files[]" multiple />
            <input type="submit" name="submit_image"/>
            <textarea name="comments"></textarea>           
            <button type="submit" name="submit_post">Submit Your Post</button>                 
        </form>         
    </body>
</html>

1 个答案:

答案 0 :(得分:0)

那是因为$uploaded仅存在于您声明它的if语句中。您需要在elseif中再次循环浏览文件或移动$uploaded$failed的声明作为for循环,将其填充到if块中,以便可以在两个路径中访问变量。

编辑 - 试试这个:

 if (!empty($_FILES["files"]["name"][0]) ) {
        $files = $_FILES["files"];
        //arrarys to include files uploaded successfully and failed
        $uploaded = array();
        $failed = array();
        //access tmp_name arrary
        foreach ($files['name'] as $position => $file_name) {
            $file_tmp = $files["tmp_name"][$position];

            $file_ext = explode(".", $file_name);
            $file_ext = strtolower(end($file_ext));

            $file_name_new = uniqid("", true) . "." . $file_ext;
            $file_destination = "uploads/" . $file_name_new;
            if (move_uploaded_file($file_tmp, $file_destination)) {
                $uploaded[$position] = $file_destination;
            } else {
                $failed[$position] = "error";
            }   
        } 
        print_r($uploaded);
    }

if (isset($_POST[submit_post])) {
        $data = array();
        $data['comments'] =  $_POST['comments'];
        $data ['pic_path'] = $uploaded;
}