How to pass a multi dimensional array to a view in

2019-02-28 19:33发布

问题:

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

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

(as you can see its the delicious API I'm playing with)

$result is an array and print_r($result) give something like this:

My problem is how to iterate through this in the view! I have been trying stuff like this,

$result = $this->deliciouslib->getRecentPosts();
$i=0;

foreach($result as $value)
{                   
     $val = 'val'.$i;           
     $data[$val]=$value;
     $i++;          
}

$this->load->view('delicious_view',$data);
return true;

And then, in the view something like...

foreach ($val0 as $value)
{
   echo $value."<br>";
}

Obviously this doesn't work, as I need all of "$val(i)"!.
Man I got BrainCramp!! I'm probably dancing around the answer, like a basketball round the hoop, but I'm totally stumnped nonetheless. Any Ideas how I can iterated throught the entire array, would be most helpful....

回答1:

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);
}


回答2:

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 "
 }


回答3:

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)**;