我是编程的新手,所以也许它很简单,但是当我运行脚本时,它给出的输出结果是未定义返回$ response,而是在数组中定义了。
已经尝试移动return语句,但无济于事
这只是一部分代码,但这是引起问题的部分
function request($opt, $data) {
$request = curl_init();
foreach ($data as $status) {
$data_string = json_encode($status);
echo "Json: " . $data_string . PHP_EOL;
$headers = array(
'Content-Type: application/json',
'Content-Length: ' . strlen($data_string)
);
$url = ENDPOINT . $opt['object'];
curl_setopt($request, CURLOPT_URL, $url);
curl_setopt($request, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($request, CURLOPT_POST, TRUE);
curl_setopt($request, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($request, CURLOPT_HTTPHEADER, $headers);
curl_setopt($request, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($request, CURLOPT_USERPWD, USERNAME . ":" . PASSWORD);
$response = curl_exec($request);
if ($response == FALSE) {
die('<p>Curl failed: ' . curl_error($request) . '</p>');
}
}
return $response;
}
答案 0 :(得分:2)
1。您需要在$response = array();
之前定义foreach()
(因为无论如何$data
是一个空数组,$response
都是未定义的。因为它是在{{ 1}})
2。在循环代码中,您正在覆盖foreach()
变量。如此修改,如下所示:
$response
将常见的curl代码放在循环外,如下所示:-
$result = curl_exec($request);
if ($result == FALSE) {
die('<p>Curl failed: ' . curl_error($request) . '</p>');
}
$response[] = $result;
答案 1 :(得分:1)
您需要在$response
语句之前定义foreach()
。
function request($opt, $data) {
$request = curl_init();
$responses = array();
foreach ($data as $status) {
$data_string = json_encode($status);
echo "Json: " . $data_string . PHP_EOL;
$headers = array(
'Content-Type: application/json',
'Content-Length: ' . strlen($data_string)
);
$url = ENDPOINT . $opt['object'];
curl_setopt($request, CURLOPT_URL, $url);
curl_setopt($request, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($request, CURLOPT_POST, TRUE);
curl_setopt($request, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($request, CURLOPT_HTTPHEADER, $headers);
curl_setopt($request, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($request, CURLOPT_USERPWD, USERNAME . ":" . PASSWORD);
$response = curl_exec($request);
$responses[] = $response;
if ($response == FALSE) {
die('<p>Curl failed: ' . curl_error($request) . '</p>');
}
}
return $responses;
}
为什么?因为如果要访问foreach()
循环之外的任何变量,则必须首先将其定义为全局变量。