![]() |
How to foreach inside view?? - Printable Version +- CodeIgniter Forums (https://forum.codeigniter.com) +-- Forum: Archived Discussions (https://forum.codeigniter.com/forumdisplay.php?fid=20) +--- Forum: Archived Development & Programming (https://forum.codeigniter.com/forumdisplay.php?fid=23) +--- Thread: How to foreach inside view?? (/showthread.php?tid=60536) |
How to foreach inside view?? - El Forum - 04-18-2014 [eluser]jcjc[/eluser] I have a foreach inside a controller that loops through the data and returns the results. I've created a foreach statement to link the results to a variable - Issue I'm having is when I pass the data to a view only one result gets returned. I've ran a var_dump and print_r and the data is being sent. Error message I get is: Message: Invalid argument supplied for foreach() Controller foreach is: Code: if ($queryTag->num_rows() > 0) on the view side the code is: Code: <?php foreach ($productTag as $tag) { ?> Thanks! How to foreach inside view?? - El Forum - 04-18-2014 [eluser]Tim Brownlaw[/eluser] Hi, The quick fix... Try changing this in your Controller Code: $row = array(); Cheers Tim How to foreach inside view?? - El Forum - 04-18-2014 [eluser]jcjc[/eluser] Thanks - any idea what I was doing wrong? How to foreach inside view?? - El Forum - 04-18-2014 [eluser]Tpojka[/eluser] You redeclared $this->data['productTag'] variable $queryTag->num_rows() amount of times without any array appening. I.E: Code: $a = 'one'; How to foreach inside view?? - El Forum - 04-19-2014 [eluser]Tim Brownlaw[/eluser] Take a good look at the code and play spot the difference! IN the new code - in the foreach - the array called $row is being created, adding a new entry on each pass. $row[] = $value creates a new entry in the array called $row each time it's run. As Tpojka stated, what you had wasn't creating an array but just a variable $this->data[‘productTag’] which is the same as saying $fred or the like... Just a plain ole variable... Not an array as you were expecting. What you would have seen from your code is $this->data[‘productTag’] containing the very last entry from your foreach loop as it was getting over written each time! When you get an error message stating that : Invalid argument supplied for foreach() means you need to g omaking sure what you're giving it is what it's wanting... Performing things like var_dump($thing_i_want_to_check_out); and see what the structure and values are... This just plain ole PHP stuff... Although arrays etc can be a little confusing at first. Hopefully that makes it a lil clearer. Cheers Tim |