简体   繁体   中英

PHP Array Manipulation, Invalid Argument Supplied for foreach()

I have an MVC structure set up in codeigniter in PHP. However, for some reason, my model results do not like being foreached over, giving me; Invalid argument supplied for foreach() . Here is the rough code of my model:

class some_model extends CI_Model
{
    function __construct()
    {
        // Call the Model constructor
        $this->load->database();
    }

    function some_func()
    {
       //Prepare return
       $return = array();

       //Do query
       $query = $this->db->query('SELECT tbl.* from tbl');

       //Get array of values
       $result = $query->result_array();

       foreach($result as $row)
       {
           $return[] = array(

               'a'                    => $row['a'],
               'b'                    => $row['b'],
               'c'                    => $row['c']
           );
       }

    return $return;
}

And the controller:

$this->load->model('some_model');
$stuff = $this->some_model->some_func();

foreach($stuff as $row)
{
   //Do something
}

But I always get an error at the foreach loop in the controller. Does anyone have an idea as to why this might be happening? I have checked, and PHP does see $stuff as an array ( is_array($stuff) returns true), so I have no idea what might be happening. I do know that the foreach loop in the model is not the problem, as it does not give me any errors, only the one in the controller does. Any tips would be appreciated. Thanks beforehand!

So, after a LOT of rooting around, I found out what my issue was, and decided to put it up here in case someone runs into the same problem. Basically, it turns out that I had some nested foreach loops inside the one that is posted in the question, so I have code like this:

foreach($stuff1 as $row)
{
   foreach($stuff2 as $row2)
   {
      //Some code
   }
}

My error was occurring in my second (nested) foreach, but for some reason, PHP gave me an error as though it was the happening in the first one (with the line number and everything). The only thing that tipped me off to the issue was the fact that the error printed the same number of times as there were rows in $stuff1 ... Can anyone comment on this behaviour with regards to PHP's error line reporting functionality? Thanks!

invalid argument for foreach loop is supplied when variable is not array. Before using foreach loop add check

if (is_array($stuff)) {...foreach loop...}

and are you sure its the $stuff part that its getting error on? maybe its $result that somehow holds non-array value returned from the query.

check what are the return values of result_array

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM