如何获得这样的json格式?

时间:2017-06-16 07:03:01

标签: php json

我想创建一个像这样的json响应,如下所示。如何通过修改下面的PHP代码来完成。我尝试了很多方法,但结果不存在。

请找到编辑器的链接

https://www.froala.com/wysiwyg-editor/docs/concepts/image/manager 我从代码中得到的当前响应是

[  
   "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);
?>

1 个答案:

答案 0 :(得分:1)

像这样编辑你的代码,改变

array_push($response, "http://cloudpanda.org/images/media/" . $name);

$response[]['url'] = "http://cloudpanda.org/images/media/" . $name;