Search code examples
phparrayslaravel-5.3implodeguzzle6

How to save implode results in array correctly?


My data_array like this :

Array ( [0] => 1 [1] => 2 [2] => 3 )

My code like this :

public function test(Request $request)
{
    $client = new GuzzleHttpClient();
    ...
    $concat_data = implode(',', $data_array);
    $result = $client->request('POST', $url, [
        'headers'=>[
            'content-type'=>'application/json',
            'Authorization'=> 'Bearer '.auth()->user()->api_token
        ], 
        'json'=>['ids'=>[$concat_data]]
    ]);
    $content = json_decode($result->getBody()->getContents());
}

If the code is executed, it does not work perfectly. It just updates the data with id = 1

But, if I try with static data like this :

public function test(Request $request)
{
    $client = new GuzzleHttpClient();
    ...
    $concat_data = implode(',', $data_array);
    $result = $client->request('POST', $url, [
        'headers'=>[
            'content-type'=>'application/json',
            'Authorization'=> 'Bearer '.auth()->user()->api_token
        ], 
        'json'=>['ids'=>[1,2,3]]
    ]);
    $content = json_decode($result->getBody()->getContents());
}

It works. It success updates the data with id = 1, id = 2, and id = 3

It seems my way of storing implode results in an array is still wrong

How can I solve this problem?

Note

If the code executed, it will update value of ids


Solution

  • implode converts an array to a string, whereas from your working static version, it looks like the API accepts a raw array. You're sending it the string "1,2,3", which it doesn't understand.

    You should be able to just use

    'json' => ['ids' => $data_array]
    

    and skip the implode call entirely.