Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/batch-file/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在PHP中构建JSON响应_Php_Json - Fatal编程技术网

在PHP中构建JSON响应

在PHP中构建JSON响应,php,json,Php,Json,我如何构建一个类似于PHP的JSON响应?详情 { "success": 1, "result": [ { "id": "293", "title": "This is warning class event", "url": "http://www.example.com/", "class": "event-warning", "start"

我如何构建一个类似于PHP的JSON响应?详情

{
    "success": 1,
    "result": [
        {
            "id": "293",
            "title": "This is warning class event",
            "url": "http://www.example.com/",
            "class": "event-warning",
            "start": "1362938400000",
            "end": "1363197686300"
        },
        {
            "id": "294",
            "title": "This is information class ",
            "url": "http://www.example.com/",
            "class": "event-info",
            "start": "1363111200000",
            "end": "1363284086400"
        }...
}
Php提供了一种方法

json_encode();

用于转换为jason格式

您必须先创建和数组:

$response = array();
$response["success"]=1;
$response["result"]=array();

$result=array();
$result["id"]="293";
$result["title"]="This is warning class event";
$result["url"]="http://www.example.com/";
$result["class"]="event-warning";
$result["start"]="1362938400000";
$result["end"]="1363197686300";
array_push($response["result"],$result);
然后使用de json_encode函数:

json_encode($response);

按如下方式构建阵列:

$json = array("success" => 1,
    "result" => array(
                    array( "id" => "293", "name" => "alex"),
                    array( "id" => "293", "name" => "alex")
                )
    );
然后在数组上使用json编码

print json_encode($json);
如果需要,还可以设置内容类型标题

header('Content-type: application/json');

将这些值放入一个数组中,并使用以下方法:

  $json = json_encode($array); 
根据需要将其转换为json。如果您这样做:

  echo $json; 

您将看到预期的Json。

使用Json\u encode函数-

要在PHP中解码JSON,请使用JSON\u decode函数-


阅读手册:
json\u encode
。在撰写此问题时,我不确定如何处理嵌入式阵列。
json_encode($your_array);
json_decode($json)