InterviewSolution
| 1. |
How to pass an array from the controller to view in CodeIgniter? |
|
Answer» A view is a webpage that shows each element of the USER interface. It cannot be called directly, you need to load the views via the controller. You can pass an array from the controller to view in CodeIgniter using below given steps:
Create a new text file and name it ciblogview.php. Save the created file in the application/views/ directory. Open the ciblogview.php file and add the below-given code to it: <html><head> <title>Blog</title></head><body> <h1>Welcome to Blog in CodeIgniter</h1></body></html>
Loading a view is executed using the following syntax: $this->load->view('name'); Where ‘name’ represents the name of the view. The below code CREATES a controller named Blog.php. This controller has the method for loading the view. <?phpclass Blog extends CI_Controller { public function index() { $this->load->view('ciblogview'); }}?>
You are allowed to paste the below-given controller code within your controller file or put it in the controller object. $data['mega_header'][] = (object) array('title' => 'image portfolio' , 'img' => 'https://complete_image_path' );$this->load->view('multiple_array', $data);Arrays are displayed as a brick[‘…’] and OBJECTS as an arrow(->). You are allowed to ACCESS an array with the brick[‘…’] and object using the arrow (->). Therefore, add the below-given code in the view file: <?php if (isset($mega_header)){ foreach ($mega_header as $key) { ?> <div class="header_item"> <img alt="<?php echo($key['title']); ?>" src="<?php echo($key->img); ?>"/> </div> <?php } }?>
Usually, data transfer from the controller to view is done through an array or an object. The array or the object is passed as the second parameter of the view load method similar to the below-given method: $data = array( 'title' => 'TitleValue', 'heading' => 'HeadingValue');$this->load->view('ciblogview', $data);The controller will look like this: <?php class Blog extends CI_Controller { public function index() { $data['title'] = "TitleValue"; $data['heading'] = "HeadingValue"; $this->load->view('ciblogview', $data); }}?>The view file will look like this: <html><head> <title><?php echo $title;?></title></head><body> <h1><?php echo $heading;?></h1></body></html> |
|