将php数组转换为json

时间:2017-09-07 09:11:24

标签: php json

我正在玩Slack /命令, 需要被发送回松弛的给定json看起来像这样。

{
 "text" : "hello world",
  "attachments": [{
                  "text" : " this is information"

                 }]
}

我试图以这种方式复制它。

$data = array(
        "text" => "hello world",
        "attachments" => array(
            "text" => "this is information",
            "author_name" => "masnad"
        )
    ); 

$this->output->set_content_type('application/json');
return $this->output->set_output(json_encode($data));

我只是不能让方括号工作,所以松弛了解。

1 个答案:

答案 0 :(得分:1)

将每个附件包装在一个数组中

$data = array(
    "text" => "hello world",
    "attachments" => array(
        array( "text" => "this is information" ),
        array( "text" => "this is another information" ),
    )
); 

使用现代PHP,为了便于阅读,您应该使用方括号表示数组:

$data = [
    "text" => "hello world",
    "attachments" => [
        [ "text" => "this is information" ],
        [ "text" => "this is another information" ],
    ]
];