【问题标题】:Message: Invalid argument supplied for foreach in CodeIgniter消息:为 CodeIgniter 中的 foreach 提供的参数无效
【发布时间】:2025-12-27 08:25:09
【问题描述】:

我在应用 Codeigniter 的过程中遇到了一些问题——创建了一个类似

的函数
function searchUnivtab() {
        $country = $this->input->post('countryKey');
        $state = $this->input->post('stateKey');
        $level = $this->input->post('level');
        $degType = $this->input->post('degType');       
        $country = str_replace('%20', ' ', $country);
        $state = str_replace('%20', ' ', $state);
        $degType = explode('~', $degType);
        $data = @$this->get->getSearchedUniversityTab($country, $state, $level, $degType[1]);
        $html = '';
        $i = 0;
        foreach($data as $d)
        {
            $html .= '<option value="'.$d['name'].'">'.$d['name'].'</option>';
        }
        echo $html; die;
    }

错误为:A PHP Error was encountered

Severity: Warning

Message: Invalid argument supplied for foreach(), Line Number: 270 位于foreach

与上述代码相关的任何帮助?

【问题讨论】:

  • 你确定 $data 是数组(我没有使用 codeigniter)?
  • @NullPointer 不,先生,它不是数组,打印'数据不是数组。'
  • 好吧,如果我删除了,我如何获取 $data 的值?有什么帮助吗?代码同上--
  • foreach 构造提供了一种迭代数组的简单方法。 foreach 仅适用于数组和对象,当您尝试在具有不同数据类型或未初始化变量的变量上使用它时会发出错误。
  • 在 $data 中得到了什么?你能给我们看看吗?

标签: php jquery codeigniter


【解决方案1】:

把下面的@去掉,看看有没有报错 所以替换

$data = @$this->get->getSearchedUniversityTab($country, $state, $level, $degType[1]);

$data = $this->get->getSearchedUniversityTab($country, $state, $level, $degType[1]);

【讨论】:

  • 非常感谢,它的工作,但错误已更改为 Message: Undefined offset: 1
  • 所以你的错误基本上在其他地方。发布字段 degType 需要一个使用 ~ 展开的值,您发布的值是多少?
  • 它显示在第 267 行,$data = $this->get->getSearchedUniversityTab($country, $state, $level, $degType[1]);
  • 正如我上面提到的,post 字段 degType 中的预期值随后使用 ~ 进行分解(因此该值可能类似于 abc~def,脚本尝试将其转换为数组并失败,这是你得到的第二个错误
【解决方案2】:
if(is_array($data)) {
    foreach($data as $d){
        $html .= '<option value="'.$d['name'].'">'.$d['name'].'</option>';
    }
} else {
    echo 'data is not an array.';
}

【讨论】:

    【解决方案3】:
    function getSearchUniversity() {
      country = jQuery('[name=countryKey]').val();
      state = jQuery('[name=stateKey]').val();
      level= jQuery('[name=level]').val();
      degType= jQuery('[name=degType]').val();
      jQuery.ajax({
        type: "POST",
        url:baseurl+ 'welcome/searchUnivtab', 
        cache: false,
        data: {countryKey: country, stateKey: state, level: level, degType: degType},
        error: function()
        {
          //notify('Error: Your request could be processed.. try again..!!');
        },
        success: function(html)
        {
          jQuery('[name=universityList]').html(html);
          return false;
        }
      }); 
    }
    

    【讨论】:

      最近更新 更多