我有一个这样的数组:
Array ( [10209064245580796] => Array ( [0] => Array ( [hashed_token] => ) [1] => Array ( [password] => ) [2] => Array ( [email] => klemen.pevc@gmail.com ) ) [10207252567926988] => Array ( [0] => Array ( [hashed_token] => ) [1] => Array ( [password] => 716b64c0f6bad9ac405aab3f00958dd1 ) [2] => Array ( [email] => milvuk@gmail.com ) ) )
我这样做了:
$users
看起来像这样:
Array ( [0] => 10209064245580796 [1] => 10207252567926988)
$arrayOfFields
看起来像这样:
Array ( [0] => hashed_token [1] => password [2] => email )
所以:
$array=array();
foreach($users as $user){
$array[$user]=array();
foreach($arrayOfFields as $getFieldValue) {
$user = '' . $user . '';
$query = "SELECT `$getFieldValue` FROM $table WHERE `$column`= $user";
$result = $mysqli->query($query);
$fetchResult = $result->fetch_assoc();
$getFieldValue = '' . $getFieldValue . '';
$finalValue = $fetchResult[$getFieldValue];
array_push($array[$user] ,array($getFieldValue=>$finalValue));
}
}
在这两个foreachs
之后,我得到了一个数组$array
,如上面第一个示例所示,我通过cURL
发送此代码:
$data = array('facebook_app_id' => $facebook_app_id, 'facebook_ids' => $facebook_ids,'values_for_custom_fields' => $array);
$endpoint_url = 'https://servis-racunara.net/api/index.php';
$curl = curl_init($endpoint_url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, Array("Authorization: Token ".$token));
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
$curl_response = curl_exec($curl);
curl_close($curl);
//you do not need to print results, this is just for debugging purposes
$result = $curl_response;
print_r($result);
因此当我执行$array
时,我会在这个端点https://servis-racunara.net/api/index.php(我正在发送一些数据,包括print_r($_POST)
)的内部脚本中得到一个这样的数组:
Array ( [facebook_app_id] => 1512823699024883 [facebook_ids] => 10209064245580796,10207252567926988[values_for_custom_fields] => Array )
因此,在密钥values_for_custom_fields
下存储了我需要处理的$array
数组。当我做print_r($_POST['values_for_custom_fields']);
它只是说'数组',当我尝试这个时:
foreach($_POST['values_for_custom_fields'] as $anything) {
echo($anything);//same with print_r
}
服务器说:
警告:为foreach()提供的参数无效
有什么想法吗?
答案 0 :(得分:2)
问题在于您选择了错误的格式来发送数据。在您的代码中,您使用 表单提交格式 ,即application/x-www-form-urlencoded
(因为它在CURL中默认使用)。 form submission formats都不支持嵌套数据(数组)。换句话说,不能在POST请求中将嵌套数组作为表单编码数据发送。
因此您必须使用其他格式发送数据。我建议使用JSON - 流行格式,允许任何级别的嵌套。在这种情况下,您必须在发送和解码之前对数据进行JSON编码 - 在端点脚本中接收它们时。您还必须为请求设置适当的Content-type
标头:application/json
。
...
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
"Authorization: Token ".$token,
"Content-type: application/json"
));
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));
...