ForEach无法识别数组

问题描述 投票:0回答:2

我正在使用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在公共函数内部的内部函数中。

php arrays foreach
2个回答
0
投票

试试这个,与我们分享输出。

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;

0
投票

有一个相同的问题,我将一个数组传递给函数中的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>";
        }
      }
}
© www.soinside.com 2019 - 2024. All rights reserved.