0

I'm trying to include a new element on a array that is filled with a query result.

For example, I have an array called $event with $event['name'], $event['date'], $event['price'].

Now, I want to add $event['category']. This one is not declared on DB event table, but $event is an array of my code. It not depends of the DB event table, no?

So... how I can put $event['cateogory'] inside event in my Class code of CodeIgniter?

I tried to put it directly, and the error show that "category" index is not defined.

$events = $this->Event_model->get_all_events();
    foreach ($events as $event) {
        $event['category'] = $this->Category_model->get_category($event['idCategory']);
    }
$data{
      'events' => $events,
}
$this->load->view('events_list',$data);

Thank you all

Zeeshan
  • 1,659
  • 13
  • 17
Ricardmc
  • 27
  • 6
  • could you post your not working code..! – Sudhir Bastakoti Apr 10 '14 at 10:59
  • read up on using mysql "join" in Code Igniter. You're on the wrong path here: http://stackoverflow.com/questions/793807/codeigniter-php-mysql-retrieving-data-with-join – Andresch Serj Apr 10 '14 at 11:14
  • 1
    foreach makes a copy of the array, so changing a copy doesn't actually alter the original. To do that, you need to specifically alter the original like so: `foreach($events as $key=>$event) { $events[$key]['category'] = ...; }` – Tularis Apr 10 '14 at 11:17

1 Answers1

0

Rather than trying to iterate over every result and adding the category (which you can do if you follow the comment made by Tularis), you should let SQL add the category by using SQL Joins.

In the Code Igniter Documentation on Active Records, you'll find information about joining Tables in Code Igniter.

Here's a simple example from the documentation adjustet to your needs:

$this->db->select('*');
$this->db->from('events');
$this->db->join('categories', 'categories.id = events.idCategory');
$query = $this->db->get();

// Produces: 
// SELECT * FROM blogs
// JOIN comments ON comments.id = blogs.id
Community
  • 1
  • 1
Andresch Serj
  • 35,217
  • 15
  • 59
  • 101