Welcome Guest, Not a member yet? Register   Sign In
How to foreach inside view??
#1

[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)
            {
                foreach($queryTag->result() as $tag)
                {
                    
                    $this->data['productTag'] = $tag->ProductTag;
                }
            }


on the view side the code is:

Code:
<?php foreach ($productTag as $tag) { ?>
     <span>&lt;?php echo $tag; ?&gt;</span>
    &lt;?php } ?&gt;

Thanks!
#2

[eluser]Tim Brownlaw[/eluser]
Hi,
The quick fix...

Try changing this in your Controller

Code:
$row = array();
if ($queryTag->num_rows() > 0)
{
  foreach($queryTag->result() as $tag)
  {
     $row[] = $tag->ProductTag;
  }
}
$this->data['productTag'] = $row;

Cheers
Tim
#3

[eluser]jcjc[/eluser]
Thanks - any idea what I was doing wrong?
#4

[eluser]Tpojka[/eluser]
You redeclared $this->data['productTag'] variable $queryTag->num_rows() amount of times without any array appening.
I.E:
Code:
$a = 'one';
$a = 'two';
.
.
.
$a = 'ten';
#5

[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




Theme © iAndrew 2016 - Forum software by © MyBB