0

I would need to insert an associative array into my existing code, to make an HTTP request.

My code at the moment:

$payload =[
    'method_id' => 2,
    'api_key'   => 5,
];
$res = $client->post('some.website', [,
    'form_params' => [
        foreach($this->payload as $key => $s_key) {
            $key => $s_key;
        }
    ],
]);

How to make now sure, each element of the $payload array is inserted into the form_params array?

I tried using:

foreach ($this->payload as $s_key => $key) {
    //?!
}

But I don't know how to proceed inside the form_params element?

Using the payload array directly inside form elements is resulting into this:

    "form_params" => [
        0 => array:2 [
          "method_id" => 2
          "api_key" => 5
        ]
    ]

What I would need is something like this:

    "form_params" => [
          "method_id" => 2
          "api_key" => 5
    ]
6
  • 1
    How about: 'form_params' => $payload, since it already is an associated array? Commented May 5, 2018 at 9:26
  • This won't work since I need the parameters directly in the forms_param array. Using the way you mentioned results in: array:1 [▼ "form_params" => array:1 [▼ 0 => array:2 [▼ "method_id" => 2 "api_key" => 5 ] ] ]
    – john_doee
    Commented May 5, 2018 at 9:29
  • 1
    No it won't, unless the $payload doesn't actually look like you're showing or if you did something like 'form_params' => [$payload] (which is not what I suggested). Demo: 3v4l.org/ohCsW Commented May 5, 2018 at 9:37
  • 1
    You also have a comma to many in: 'some.website', [,. It should be 'some.website', [ Commented May 5, 2018 at 9:37
  • @MagnusEriksson I edited my first post.
    – john_doee
    Commented May 5, 2018 at 11:34

1 Answer 1

1

You should just be able to just use the $payload variable directly, like so:

$res = $client->post('some.website', [
    'form_params' => $payload,
]);
2
  • I'm not quite sure why you seem to be getting that extra array in-between the 'form_params' key and the "payload"? See the code here: https://3v4l.org/JMNHc, I use the $payload variable as above and the payload associative array ends up directly under the 'form_param' key. Commented May 5, 2018 at 11:58
  • I think the OP's code looks different from the code in the question, since the OP claims to get a result, while the code in the question would throw a syntax error (the trailing comma). I'm bailing now. Don't want to fall deeper into the rabbit whole :-p Commented May 5, 2018 at 12:49

Not the answer you're looking for? Browse other questions tagged or ask your own question.