Welcome Guest, Not a member yet? Register   Sign In
controller array to view (noob question)
#1

[eluser]mwolf[/eluser]
I'm trying to run a query on a Controller file, set the correct params and then send all of that data in a array to the view and loop over it. I don't want to pass an array of what exactly is in the database, I first want to modify the values a bit and then pass it to the view. Something like below:

Code:
CONTROLLER:

$query = $this->db->query('SELECT * FROM products');

if ($query->num_rows() > 0)
{
    foreach ($query->result() as $row)
    {
        $name = $row->name;
        $description = substr($row->description, 0, 200);
        $image = "http://domain.com/". $row->image;
        
        $data['feed'][] = $name, $description, $image;
        
    }
}

$data['main_content'] = 'home';
$this->load->view('template', $data);

How can I build the array after I set the variables?
#2

[eluser]jedd[/eluser]
Hi mwolf and welcome to the CI forums.

Unless description is hugely long, I'd just pass the whole thing over to the view - and do the 200char limit in the view.

Similarly I'd insert the http://domain.com/ string to the image URL in the view, too.

So - in the controller (or ideally the model) I'd do:
Code:
$query = $this->db->query('SELECT * FROM products');

if ($query->num_rows() > 0)
    return  $query->result_array();   // if in model
    $data['results'] = $query->result_array();  // if in controller

Oh, I use arrays in preference to objects - but you can shuffle this back to using objects if you prefer them.

In the view you can then do something like this:
Code:
foreach ($results as $result)
    {
        echo $result['name'];
        echo substr ($result['description'], 0, 200);
        echo "http://domain.com/". $result['image'];   // or anchor() or similar
    }

If 'description' is potentially huge, and you're tight on memory, change your model method to accept a limiting parameter, and cull the description array element down to that arbitrary length as you pull it out of the db.

There are plenty of ways to do all this, of course, but this is how I'd do it.
#3

[eluser]mwolf[/eluser]
Ok, that makes sense. It seems to be working fine this way. Thanks so much.




Theme © iAndrew 2016 - Forum software by © MyBB