我正在用foreach()循环遍历一个数组,但由于某种原因,这一行似乎不像我的数组。这很奇怪,因为我有另一个foreach在另一个正确工作的文件中处理这个数组。我试过将它转换为一个数组,但这只会让我返回给其他函数和嵌套数组的空字符串。
阵列结构:
Array (
[0] => http://example.com/example.html
[1] => http://developer.com/test.html
)
PHP
/*
* Sends forms post submissions to a second source
*
*/
public function send_to_third_party(){
//this is how we read options from the options database as seen in options.php
//get settings
$formIdsArray = explode(',', get_option('fts_form_id'));
$formUrlsArray = explode(',', get_option('fts_forward_url'));
print_r($formUrlsArray);
add_action("gform_post_submission", "post_again", 10, 2);
function post_to_url($url, $data) {
// use key 'http' even if you send the request to https://...
$options = array(
'http' => array(
'header' => "Content-type: application/x-www-form-urlencoded'r'n",
'method' => 'POST',
'content' => http_build_query($data),
),
);
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
}
function post_again($entry, $form){
//if this form's ID matches the required id, forward it to corresponding URL
if(get_option('fts_forward_url')){ //check for empty forwarding URLs
if(is_array($formUrlsArray))
{
foreach($formUrlsArray as $key => $formUrl){
//post_to_url($formUrl, $entry);
}
}
else
{
echo "<pre>"; print_r($formUrlsArray); echo "</pre>";
}
}
}
}
误差Warning: Invalid argument supplied for foreach() in *path* on line *line*
编辑:foreach是在公共函数的内部函数中
试试这个,和我们分享一下输出。
if(is_array($formUrlsArray))
{
foreach($formUrlsArray as $key => $formUrl){
post_to_url($formUrl, $entry);
}
}
else
{
echo "<pre>"; print_r($formUrlsArray); echo "</pre>";
}
也考虑类型转换$formUrlsArray:
$formUrlsArray = (array) $formsUrlArray;
有同样的问题,我在一个函数中传递一个数组给foreach。在将数组传递给foreach之前对其进行类型转换解决了这个问题。
那么按照下面的方式插入$formUrlsArray = (array) $formUrlsArray
,它应该可以工作。
function post_again($entry, $form){
//if this form's ID matches the required id, forward it to
//corresponding URL
if(get_option('fts_forward_url')){ //check for empty forwarding URLs
$formUrlsArray = (array) $formUrlsArray
if(is_array($formUrlsArray))
{
foreach($formUrlsArray as $key => $formUrl){
//post_to_url($formUrl, $entry);
}
}
else
{
echo "<pre>"; print_r($formUrlsArray); echo "</pre>";
}
}
}