Search code examples
phpjsonlaraveldynamic-arrays

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


I am trying to create an a JSON response in this format:

{
  "id": "",
  "goalLink": [{
       "iconUrl": "",
       "title": ""
  }]
}

I declared the variables as

$id;
$goalLink = [];

Then within a constructor i created

$this->id = 123;
$this->goalLink = [
     'iconUrl' => null,
     'title' => null
];

now when i do something like this in a function

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

}

but this is the $data format what the example() is sending to the API

{
  "id": "",
  "goalLink": {
       "iconUrl": "",
       "title": ""
  }
}

I checked in various other forums but could not find a solution. Can someone please help me out here. I am not sure where i am going wrong.


Solution

  • Wrapping your associative array with iconUrl and title inside an indexed array would provide the additional wrapper.

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