Welcome Guest, Not a member yet? Register   Sign In
show results from simple array
#1

[eluser]raduenea[/eluser]
How to show results from array with Foreach ?

I saw that to show from sql query is:
Code:
$query = $this->db->query("YOUR QUERY");

foreach ($query->result() as $row)
{
   echo $row->title;
   echo $row->name;
   echo $row->body;
}

But if I have in controller:
Code:
$data['array'] = array('abstracte' => 'Abstracte', 'munti' => 'Munti', 'oameni' => 'Oameni');

in views I try something like:
Code:
foreach ($array->result() as $key => $value)
{
   echo $key->$value;
}


Of course I can use like the following but I'm not sure if codeigniter have a class to show results from simple array like an sql query.
Code:
foreach ($array as $key => $value)
{
    echo $key . ' -> ' . $value . '<br>';
}

Thank you
#2

[eluser]boltsabre[/eluser]
The ->result() is for db objects, it won't work on normal arrays.

And please don't call a variable "array" as you have done with $data['array'], you'll just cause yourself bugs and headaches galore! Call it something meaningful!

To the best of my knowledge there is not an "array" function/helper build into CI, but you could easily build your own helper file/function if you need to re-use this functionality often.

Read up on the section about helpers:
http://ellislab.com/codeigniter/user-gui...lpers.html
And creating/using your own helper
http://stackoverflow.com/questions/80439...new-helper

Then you'd just need a function something like this:
Code:
function echo_array($array_to_echo = null) {
   if ($array_to_echo === null || !is_array($array_to_echo) || count($array_to_echo) < 1) {
      //no array passed to function, or something was passed, but not an array
      return false;
   }
  
   $return_str = '';
   foreach ($array_to_echo as $key => $value) {
      $return_str .= "$key -> $value";
   }
   return $return_str;
}

The above function is not tested or anything, it may contain bugs. It is also VERY simple and not very robust, you'd maybe want to put in some checking for if it is a numeric array vs associative, pass in a second parameter with is your "break text" (in the above function that is the ->, etc. Also it wont handle nested arrays... you could do lots with this, should be a fun little project for you!

But you get the idea, happy coding!!!
#3

[eluser]Pert[/eluser]
Code:
foreach ($query->result() as $row)
{
   echo '<pre>'.print_r($row, true).'</pre>';
}




Theme © iAndrew 2016 - Forum software by © MyBB