Message: Invalid argument supplied for foreach in

2019-02-21 08:23发布

问题:

i am facing few issues during an application of Codeigniter -- Created an function like

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;
    }

Error as: A PHP Error was encountered

Severity: Warning

Message: Invalid argument supplied for foreach(), Line Number: 270 which is at foreach line

Any help related to above code ?

回答1:

Remove @ in the following line to see if it produces any error so replace

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

with

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


回答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;
    }
  }); 
}