我正在尝试以这种格式创建一个JSON响应:
{
"id": "",
"goalLink": [{
"iconUrl": "",
"title": ""
}]
}
我将变量声明为
$id;
$goalLink = [];
然后在我创建的构造函数中
$this->id = 123;
$this->goalLink = [
'iconUrl' => null,
'title' => null
];
现在当我在一个函数
中执行类似的操作时public function example() {
$client = API::client();
$url = "some url here";
$data = [
'id' => $this->id,
'goalLink' => [
'iconUrl' => $this->goalLink['iconUrl'],
'title' => $this->goalLink['title']
]
];
$client->post($url, ['json' => $data]);
}
但这是示例()发送到API
的$ data格式{
"id": "",
"goalLink": {
"iconUrl": "",
"title": ""
}
}
我在各种其他论坛中查了但是找不到解决方案。有人可以帮帮我吗。我不知道我哪里出错了。
答案 0 :(得分:1)
在索引数组中使用iconUrl和title包装关联数组将提供额外的包装。
public function example() {
$client = API::client();
$url = "some url here";
$data = [
'id' => $this->id,
'goalLink' => [
[
'iconUrl' => $this->goalLink['iconUrl'],
'title' => $this->goalLink['title']
]
]
];
$client->post($url, ['json' => $data]);
}