PHP数组到JSON对象

编程入门 行业动态 更新时间:2024-10-10 09:19:26
PHP数组到JSON对象 - 如何操作?(PHP Array to JSON Object - How to manipulate?)

我有一个ajax应用程序。 它基本上将图像上传到文件夹,然后PHP抓取它们并将它们放入一个数组中。 从那里它是json_encodeded并通过echo发回。 alert(responseText)给了我json版本。 在我使用console.log()将变量设置为json.parse() ,它就像数组一样精细。 该数组看起来基本上是这样的:

1 IMAGE1.jpg 2 IMAGE2.jpg 3 IMAGE3.jpg 4 IMAGE4.jpg 5 IMAGE5.jpg

等等

我知道它现在是一个javascript / json对象。 不幸的是,我找不到任何有关操纵此对象的信息来获取所有图像名称和最后一个数组类型,这是上传的真正成功或失败。 任何人都可以指向我一些文档或操作方法,并将信息外推到数组中。 最后我试图动态显示这些图像,但我假设通过上传它们并不都具有相同的名称。

所以我希望抓住所有.jpg / .png。/ gif等并获取这些文件名,然后使用innerHTML使用循环创建一堆带有正确文件名的<img>标签。 同样,处理数组中的最后一个部分,只是文本说明上传是否完全成功。

我应该不使用JSON吗? 我的代码如下。

PHP

$dirhandler = opendir(UPLOAD_DIR); //create handler to directory //read all the files from directory $nofiles=0; while ($file = readdir($dirhandler)) { //if $file isn't this directory or its parent //echo "FILE SYSTEM: " . $file . "<br/>"; //add to the $files array if ($file != '.' && $file != '..') { $nofiles++; $files[$nofiles]=$file; } //end of if loop } //end of while loop //json_encode($files); if (!$success) { $nofiles++; $files[$nofiles] = "Unable to upload file"; exit; } else { $nofiles++; $files[$nofiles] = "File Upload Successfully"; } echo json_encode($files);

JAVASCRIPT

if (xhr.readyState === 4 && xhr.status === 200) { progressBar.value="100"; progressText = "Upload Complete!"; progressStatus.innerHTML = progressText; var imageNames = JSON.parse(xhr.responseText); alert(imageNames); } else if (xhr.readyState === 0 || xhr.readyState === 1) { progressBar.value = "25"; progressText = "Starting Upload.."; progressStatus.innerHTML = progressText; } else if (xhr.readyState === 2) { progressBar.value = "50"; progressText = "Almost Done..."; progressStatus.innerHTML = progressText; } else if (xhr.readyState === 3) { progressBar.value = "75"; progressText = "So Close!"; progressStatus.innerHTML = progressText; } else if (xhr.status === 404 || xhr.status === 500) { alert("Your Upload Request failed."); }

I have an ajax application. It basically uploads images to a folder then PHP grabs them and puts them into an array. From there it is json_encodeded and sent back through echo. alert(responseText) gives me the json version. After I set a variable to json.parse(), with console.log() it comes out fine as an array. The array looks basically like this:

1 IMAGE1.jpg 2 IMAGE2.jpg 3 IMAGE3.jpg 4 IMAGE4.jpg 5 IMAGE5.jpg

etc.

I understand it is now in a javascript/json object. Unfortunately I can't find any information about manipulating this object to grab all the image names and the last array type which is a true success or failure of the upload. Can anyone point me to some documentation or a way to manipulate this and extrapolate the information into an array. In the end i'm trying to dynamically show these images but I am assuming through the upload they do not all have the same name.

So my hope is to grab all .jpg/.png./gif etc. and grab those filenames and then using innerHTML create a bunch of <img> tags with the correct filename using a loop. As well, handling the last piece in the array which is just text saying if the upload was fully successful or not.

Should I not be using JSON? My code is below.

PHP

$dirhandler = opendir(UPLOAD_DIR); //create handler to directory //read all the files from directory $nofiles=0; while ($file = readdir($dirhandler)) { //if $file isn't this directory or its parent //echo "FILE SYSTEM: " . $file . "<br/>"; //add to the $files array if ($file != '.' && $file != '..') { $nofiles++; $files[$nofiles]=$file; } //end of if loop } //end of while loop //json_encode($files); if (!$success) { $nofiles++; $files[$nofiles] = "Unable to upload file"; exit; } else { $nofiles++; $files[$nofiles] = "File Upload Successfully"; } echo json_encode($files);

JAVASCRIPT

if (xhr.readyState === 4 && xhr.status === 200) { progressBar.value="100"; progressText = "Upload Complete!"; progressStatus.innerHTML = progressText; var imageNames = JSON.parse(xhr.responseText); alert(imageNames); } else if (xhr.readyState === 0 || xhr.readyState === 1) { progressBar.value = "25"; progressText = "Starting Upload.."; progressStatus.innerHTML = progressText; } else if (xhr.readyState === 2) { progressBar.value = "50"; progressText = "Almost Done..."; progressStatus.innerHTML = progressText; } else if (xhr.readyState === 3) { progressBar.value = "75"; progressText = "So Close!"; progressStatus.innerHTML = progressText; } else if (xhr.status === 404 || xhr.status === 500) { alert("Your Upload Request failed."); }

最满意答案

imageNames是一个非常特殊的对象 - 像使用任何普通的javascript对象一样使用它。 例如: imageNames[2]将为您提供第二个图像名称。

但是,如果生成一个json_encode()将理解为实际JS数组的数组,那么生活会更容易。 在PHP中,为每个图像包含一个条目,而不是使用显式索引:

$files = array();
$entries = scandir(UPLOAD_DIR);
foreach ($entries as $entry) {
    if (is_file(UPLOAD_DIR.'/'.$entry)) {
        $files[] = $entry;
    }
}
if (!$files) {
    // signal an error with an actual HTTP error code!
    header('Content-Type: application/json', false, 500);
    echo json_encode(array('error'=>'upload failed'));
} else {
    header('Content-Type: application/json');
    echo json_encode($files);
}
 

但是,我怀疑您在处理文件时应该收集文件名。 使用带有<input type="file" name="images[]">等输入元素的上传表单,然后使用以下内容上传到脚本:

function process_uploaded_files($files, $destdir, $nametmpl) {
    $moved = array();
    foreach ($files['error'] as $key => $error) {
        $newname = FALSE;
        if ($error===UPLOAD_ERR_OK) {
            $source = $files['tmp_name'][$key];
            $destname = sprintf($nametmpl, $key);
            $dest = "{$destdir}/{$destname}";
            if (move_uploaded_file($source, $dest)) {
                // success!
                $newname = $destname;
            }
        }
        $moved[$key] = $newname;
    }
    return $moved;
}

function filename_to_url($filename) {
    // or whatever
    return ($filename) ? '/images/'.$filename : $filename;
}    

$uploaded_files = process_uploaded_files($_FILES['images'], UPLOAD_DIR, 'Image%03d');

// you should always return URLs of resources (not bare filenames) to be RESTful
$new_urls = array_map('filename_to_url', $uploaded_files);
header('Content-Type: application/json');
echo json_encode($new_urls);

imageNames is a nothing-special object--use it like you would use any normal javascript object. E.g.: imageNames[2] will give you the second image name.

However, you life will be much easier if you produce an array that json_encode() will understand as an actual JS array. In your PHP, include an entry for each image instead of using explicit indexes:

$files = array();
$entries = scandir(UPLOAD_DIR);
foreach ($entries as $entry) {
    if (is_file(UPLOAD_DIR.'/'.$entry)) {
        $files[] = $entry;
    }
}
if (!$files) {
    // signal an error with an actual HTTP error code!
    header('Content-Type: application/json', false, 500);
    echo json_encode(array('error'=>'upload failed'));
} else {
    header('Content-Type: application/json');
    echo json_encode($files);
}
 

However, I suspect that you should be gathering your file names when you process them. Use an upload form with input elements like <input type="file" name="images[]">, then upload to a script with this:

function process_uploaded_files($files, $destdir, $nametmpl) {
    $moved = array();
    foreach ($files['error'] as $key => $error) {
        $newname = FALSE;
        if ($error===UPLOAD_ERR_OK) {
            $source = $files['tmp_name'][$key];
            $destname = sprintf($nametmpl, $key);
            $dest = "{$destdir}/{$destname}";
            if (move_uploaded_file($source, $dest)) {
                // success!
                $newname = $destname;
            }
        }
        $moved[$key] = $newname;
    }
    return $moved;
}

function filename_to_url($filename) {
    // or whatever
    return ($filename) ? '/images/'.$filename : $filename;
}    

$uploaded_files = process_uploaded_files($_FILES['images'], UPLOAD_DIR, 'Image%03d');

// you should always return URLs of resources (not bare filenames) to be RESTful
$new_urls = array_map('filename_to_url', $uploaded_files);
header('Content-Type: application/json');
echo json_encode($new_urls);

                    
                     
          

更多推荐

本文发布于:2023-07-06 07:44:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1047462.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   对象   PHP   JSON

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!