Php 如何获得这样的json格式?
我想创建一个json响应,如下所示。如何通过修改下面的php代码来实现。我尝试了很多方法,但都没有结果 请找到编辑器的链接 我从代码中得到的当前响应如下Php 如何获得这样的json格式?,php,json,Php,Json,我想创建一个json响应,如下所示。如何通过修改下面的php代码来实现。我尝试了很多方法,但都没有结果 请找到编辑器的链接 我从代码中得到的当前响应如下 [ "http://cloudpanda.org//images/media/01fe5273acbd47e413b02bbcfae5a20ac868d037.jpg", "http://cloudpanda.org//images/media/022fa4051066da105688a8ca0f83d222cef3739d.
[
"http://cloudpanda.org//images/media/01fe5273acbd47e413b02bbcfae5a20ac868d037.jpg",
"http://cloudpanda.org//images/media/022fa4051066da105688a8ca0f83d222cef3739d.jpg",
]
我需要代码的预期响应如下:
[
{
"url":"http://cloudpanda.org//images/media/01fe5273acbd47e413b02bbcfae5a20ac868d037.jpg",
},
{
"url":"http://cloudpanda.org//images/media/022fa4051066da105688a8ca0f83d222cef3739d.jpg",
},
]
当前php代码如下所示:
<?php
// Array of image links to return.
$response = array();
// Image types.
$image_types = array(
"image/gif",
"image/jpg",
"image/pjpeg",
"image/jpeg",
"image/pjpeg",
"image/png",
"image/x-png"
);
// Filenames in the uploads folder.
$fnames = scandir("images/media/");
// Check if folder exists.
if ($fnames) {
// Go through all the filenames in the folder.
foreach ($fnames as $name) {
// Filename must not be a folder.
if (!is_dir($name)) {
// Check if file is an image.
if (in_array(mime_content_type(getcwd() . "/images/media/" . $name), $image_types)) {
// Add to the array of links.
array_push($response, "http://cloudpanda.org/images/media/" . $name);
}
}
}
}
// Folder does not exist, respond with a JSON to throw error.
else {
$response = new StdClass;
$response->error = "Images folder does not exist!";
}
$response = json_encode($response);
// Send response.
echo stripslashes($response);
?>
像这样编辑代码,更改
array_push($response, "http://cloudpanda.org/images/media/" . $name);
到
这里的问题是什么?我需要得到上面json代码中的响应变量。目前我只得到一个url列表,我只需要像这样得到“url”:“”,你的链接是blandI更新了我的问题,请检查
$response[]['url'] = "http://cloudpanda.org/images/media/" . $name;