【问题标题】:How to get a json format like this?如何获得这样的json格式?
【发布时间】:2017-06-16 16:28:56
【问题描述】:

我想创建一个这样的 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);
?>

【问题讨论】:

  • 您有什么问题?
  • 我需要获取响应变量作为上面的json代码。目前我只得到一个 url 列表,只有我需要像这样 "url":"i.froala.com/assets/photo1.jpg",
  • 你的链接是平淡的
  • 我更新了我的问题,请检查

标签: php json


【解决方案1】:

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-03
    • 1970-01-01
    • 2019-06-27
    • 1970-01-01
    • 2021-03-27
    • 1970-01-01
    相关资源
    最近更新 更多