我正在尝试使用此代码为http请求创建方法,但它只会获取1组键和值对(" key_1" =>" value_1& #34)。我如何获得所有数组键及其值?
<?php
$userPostData = [
'key_1' => "value_1",
'key_2' => "value_2"
];
foreach($userPostData as $key => $value) {
$response = $client->post($apiUrl, [
'json' => [
$key => urlencode($value),
],
'verify' => false
]);
}
答案 0 :(得分:1)
您可以使用array_map对数组值进行urlencode。另外,我想你忘了把数组编码为json,所以我为你做了:
$userPostData = [
'key_1' => "value_1",
'key_2' => "value_2"
];
$userPostData = array_map('urlencode', $userPostData);
$response = $client->post($apiUrl, [
'json' => json_encode($userPostData),
'verify' => false
]);