Use of foreach in the Controller and use of output it in the view
I use codeigniter. How can put foreach in the Controller and use only of output it in the view.(i not want put foreach in the view) ?
foreach ($output->result() as $row)
{
echo '<option>'.$row->name.'</option>';
}
This is my view now:
<select>
<option disabled="disabled" value="">selected</option>
<?php
foreach ($output->result() as $row) {
echo '<op开发者_运维百科tion>'.$row->name.'</option>';
}
?>
</select>
I want this in the view:
<select>
<option disabled="disabled" value="">selected</option>
<?php
echo $output_foreach_from_Controller;
?>
Although the logic wants the foreach to be inside the view (it's a presentational thing, after all, and Controllers shouldn't do any data manipulation of sorts. Since you're using a db method, you might want to put that in the model, although "logically" wrong too...)
Anyway, coming to your question...You can assign it to a variable, and pass that to the view:
In controller:
function whatever()
{
$string = '';
foreach ($output->result() as $row) {
$string .= '<option>'.$row->name.'</option>';
}
$data['foreach_output'] = $string;
$this->load->view('viewfile',$data);
}
in view:
<select>
<?php echo $foreach_output;?>
</select>
Maybe you can use 'form_dropdown' form_helper. See: http://codeigniter.com/user_guide/helpers/form_helper.html I hope this help to you.
I think in the controller you can assign the value ... to a variable and then pass that variable to the view. See something like given below:
<?php
$variable = "";
foreach ($output->result() as $row) {
$variable = $variable . '<option>'.$row->name.'</option>';
}
$data["option_values"] = $variable;
$this->load->view('view-name', $data);
?>
And then echo the "$option_values" variable in the view where you wan
I think you should really put the foreach in the view. You can also use the template version of foreach to make it look nicer:
<select>
<option disabled="disabled" value="">selected</option>
<?php foreach ($output->result() as $row): ?>
<option><?php echo $row->name.; ?></option>
<?php endforeach; ?>
</select>
The reason for this is that if you generate HTML in the controller it's not immediately obvious what is being output.
精彩评论