在PHP中将嵌套数组转换为json,无需额外编码

时间:2017-07-05 15:21:42

标签: php arrays json

我想将我的数组转换为Json字符串,并使用Firebase Cloud Messaging Server将其用于发送消息 我的阵列是:

$data = array(
                "to" => "cMbucIFcJMA:APA91bH_Wq0sPrMhTmhJ9gPJX7GUsRo...",
                "notification" => 
                    array(
                        "body" => "sadeq",
                        "title" => "test notification"
                    )
                );

当我使用json_encode($data)时我的后面的字符串是:
{"to":"cMbucIFcJMA:APA91bH_Wq0sPr.... \n","notification":"Array"}
如何在我的通知字符串中没有Array的情况下将此数组转换为有效的Json?

我的完全功能是:

public function SendFromPost(){


                $data = array(
                    "to" => "cMbucIFcJMA:APA91bH_..... ",
                     "notification" => 
                    array(
                        "body" => "sadeq",
                        "title" => "test notification"
                    )
                );






                  $ch = curl_init();
                  curl_setopt($ch , CURLOPT_URL , "https://fcm.googleapis.com/fcm/send");
                  curl_setopt($ch , CURLOPT_POST , 1);
                  curl_setopt($ch , CURLOPT_POSTFIELDS , $data );
                  curl_setopt($ch , CURLOPT_RETURNTRANSFER , true);

                      $headers = [
                        'Content-Type: application/json \n',
                        'Authorization: key=AIzaS.......'
                      ];

                  curl_setopt($ch , CURLOPT_HTTPHEADER , $headers);

                  $server_output = curl_exec($ch);
                  curl_close($ch);


                 return var_dump(json_encode($data));

            }

我的代码是正确的。但我不知道为什么我的php会这样。

1 个答案:

答案 0 :(得分:1)

您的代码有效。您的嵌套数组后,您还有一个额外的;无效。

<?php
$data = array(
                    "to" => "cMbucIFcJMA:APA91bH_Wq0sPrMhTmhJ9gPJX7GUsRo...",
                    "notification" => 
                        array(
                            "body" => "sadeq",
                            "title" => "test notification"
                        )
                    );

var_dump(json_encode($data));

<强>产量

string(115) "{"to":"cMbucIFcJMA:APA91bH_Wq0sPrMhTmhJ9gPJX7GUsRo...","notification":{"body":"sadeq","title":"test notification"}}"