2

I have CodeIgniter question. How can I pass an array from controller to view? Here is my code that doesn't work:

controller:

$data_part13['header3_item'][] = array('title' => 'first image 1' , 'img' => 'https://encrypted-tbn0.google.com/images?q=tbn:ANd9GcQoshslL3aMNzG50708domqPSA4ouPjk_wA7jCpVRUH3k8zVdn9' );

$this->load->view('part_1_3', $data_part13);

and view:

<div id="header3">
    <div id="header3-inner">
        <?php
        if (isset($header3_item)){
            foreach ($header3_item as $key) {
        ?>
                <div class="header3-item">
                    <img alt="<?php echo($key->title); ?>" src="<?php echo($key->img); ?>"/>
                </div>
        <?php
            }
        }
        ?>
    </div>
</div>
Irakli
  • 1,151
  • 5
  • 30
  • 55

2 Answers2

6

You did it correctly (kinda). You passed an array to the view, but your problem was that you were using an object in the view. You should have instead done something like this:

$data_part13['header3_item'][] = (object) array('title' => 'first image 1' , 'img' => 'https://encrypted-tbn0.google.com/images?q=tbn:ANd9GcQoshslL3aMNzG50708domqPSA4ouPjk_wA7jCpVRUH3k8zVdn9' );

$this->load->view('part_1_3', $data_part13);

The view part can stay the same.

  • Thank you for answer, It worked for me. But I can't still get it why I need "(object)" ? is it PHP standard or Codeigniter method? – Irakli Jan 06 '12 at 10:18
  • 4
    Well, think of objects as an arrow and arrays as a brick. They both are made out of atoms, but they look differently. You can access an object with the `->` (arrow) and an array with the `['..']` (brick) but you **can not** access the objects data with an array call. –  Jan 06 '12 at 10:50
2

You're passing it in correctly, but you're not accessing it correctly from the view. Instead of $key->title, you need to use $key['title'];

Dan Blows
  • 20,846
  • 10
  • 65
  • 96