尝试以下面提到的 json 格式创建动态数组

Trying to create a dynamic array in the below mentioned json format

我正在尝试以这种格式创建一个 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]);

}

但这是 example() 发送到 API

的 $data 格式
{
  "id": "",
  "goalLink": {
       "iconUrl": "",
       "title": ""
  }
}

我查看了其他各种论坛,但找不到解决方案。有人可以帮我解决这个问题吗?我不确定我哪里错了。

在索引数组中使用 iconUrl 和标题包装关联数组将提供额外的包装器。

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]);
}