如何在php中构建这个json

时间:2016-12-05 12:18:54

标签: javascript php json

即时通讯使用php发送推送但我的json对象正在获得我想要的方式...

我需要我的json是这样的:

{
    "to": ["xxx"],
    "data": {
        "title": "dw",
        "body": "dw",
        "actions": [
            { "icon": "emailGuests", "title": "Candidatar-me", "callback": "app.emailGuests", "foreground": true},

        ]
    }
}

但是我得到了这个:

  {
  "to": "xxx",
  "data": {
    "title": "dw",
    "body": "dw",
    "actions": {
      "icon": "send.ico",
      "title": "EMAIL GUESTS",
      "callback": "app.callbackName",
      "foreground": true
    }
  }
}

我正在构建我的json:

$fields = array (  'to' =>   $row1['fcm_registered_id'] ,  
                    'priority' => "high",  
                    'data' => array("title" =>$titlepost, 
                                    "body"=> $msg, 
                                    "actions" => array('icon' => 'send.ico', 
                                    'title' => 'EMAIL GUESTS',
                                    'callback' => 'app.callbackName',
                                    'foreground' => true 
                                    )
                    ), 
                );

1 个答案:

答案 0 :(得分:3)

请记住json_encode将非数字索引数组转换为对象。这就是为什么你得到对象而不是对象数组。它足以用另一个数组包装这个数组。这是固定代码:

$fields = array ( 
    'to' =>   array( $row1['fcm_registered_id'] ),
    'data' => array(
        "title" =>$titlepost, 
        "body"=> $msg, 
        "actions" => array(
                array(
                    'icon' => 'send.ico', 
                    'title' => 'EMAIL GUESTS',
                    'callback' => 'app.callbackName',
                    'foreground' => true 
                )
        )
    )
);

以下是工作示例:http://phpio.net/s/1n0e

小注意:尝试使用新的数组语法:[]而不是旧的array()