How to pass a multi dimensional array to a view in CodeIgniter

后端 未结 3 924
栀梦
栀梦 2021-01-24 00:36

this is really doing my nut in. I\'m passing a multidimensional array to a view like this:

$res = $this->deliciouslib->getRecentPosts();

相关标签:
3条回答
  • 2021-01-24 01:10

    Assuming that $this->deliciouslib->getRecentPosts() returns an iterable, you can try:

    $data['delicious_posts'] = $this->deliciouslib->getRecentPosts();
    

    and pass it to the view normally. Then, on the view you do something like:

    foreach($delicious_posts as $delicious_post){
       print_r($delicious_post);
    }
    
    0 讨论(0)
  • 2021-01-24 01:31

    Answer to your problem could be way of calling data from the array. Possible solutions:

    1. Get the data in an array with index.

      $data['**result**']=$this->deliciouslib->getRecentPosts();
      
    2. Now since the result of getRecentPosts() is an array of data, pass it to view

      $this->load->view('view_name', $data);
      
    3. If the result is an array, on View Page, access it via RIGHT INDEXING

      $result[0-9]['col_name'] e.g **var_dump($result[9]['Title']**);
      

      Otherwise if it is an array of objects,

      $result[0-9]=>col_name<br> e.g **var_dump($result[9]=>title)**; 
      
    0 讨论(0)
  • 2021-01-24 01:33

    In CodeIgniter, when you pass an array to the view every key is set a simple variable:

     $data = array('foo' => 'bar');
     $this->load->view('myview', $data)
    
     // In your view
     echo $foo; // Will output "bar"
    

    So if you want to pass an array, just set a value as an array:

     $data = array('foo' => array('bar1', 'bar2') );
     $this->load->view('myview', $data)
    
     // In your view
     foreach($foo as $bar) {
       echo $bar . " "; // Will output "bar1 bar2 "
     }
    
    0 讨论(0)
提交回复
热议问题