Welcome Guest, Not a member yet? Register   Sign In
format string in controller then use it as a function in view
#1

[eluser]runrun[/eluser]
Hi,

I have a string similar this in controller:

Code:
'close time:' . mktime($rows['close_time']) . 'timeleft:' mktime($rows['close_time']-$rows['current_time'])

I want to use it in the view file, like this:

Code:
<?php foreach($query->result_array() as $rows): ?>
<div>&lt;?=formated_time($rows['close_time'], $rows['close_time'], $rows['current_time'])?&gt;</div>
&lt;?php endforeach();?&gt;

Is there any features in CI allow to do this ?
#2

[eluser]runrun[/eluser]
actually I can use sprintf function in the controller to format the string, but does any one knows how can make the function available in the viewfile ?
#3

[eluser]runrun[/eluser]
OK this is a so easy question, I shouldn't ask at all.
#4

[eluser]xwero[/eluser]
Why not do the subtraction before you add the rows to the view file then you can do
Code:
&lt;?php foreach($rows as $row): ?&gt;
<div>close time : &lt;?php echo $row['close_time'] ?&gt; timeleft : &lt;?php echo $row['time_left'] ?&gt;</div>
&lt;?php endforeach();?&gt;
It's better not to use database methods, result_array, in view files. You best keep those in your model.
#5

[eluser]runrun[/eluser]
This is an extension question according to your suggestion.

How could I use the database method in the control and get the result to view ? I never know how to do this before, an simple code of the controller and the view would be appreciate.
#6

[eluser]xwero[/eluser]
Code:
// model
function get_shop_hours()
{
   $query = $this->db->select('open_time,close_time')->get('shops'); // php5
   return $query->result_array();
}
// controller
$shop_hours = $this->shop_model->get_shop_hours();
$current_time = time();

foreach($shop_hours as $key=>$shop)
{
   $shop_hours[$key]['time_left'] = $shop['close_time']-$current_time;
}

$data['shop_hours'] = $shop_hours;
//view
&lt;?php foreach($shop_hours as $shop): ?&gt;
<div>close time : &lt;?php echo $shop['close_time'] ?&gt; timeleft : &lt;?php echo $shop['time_left'] ?&gt;</div>
&lt;?php endforeach();?&gt;
This code will not work as i don't know which date format you are using.

You could do this in the sql statement too but then you are committing the model to one database, the mysql example
Code:
$query = $this->db->select('open_time,close_time,(close_time-UNIX_TIMESTAMP()) time_left')->get('shops');




Theme © iAndrew 2016 - Forum software by © MyBB