【发布时间】:2020-09-16 14:12:39
【问题描述】:
我有两 (2) 个在 codeigniter 下使用 PHP 的 foreach 循环。它们在控制器中调用相同的函数。我想在第一个循环上获得值“gross_1”,然后将其扣除到第二个循环上的“gross_2”以获得“final_gross”。
这是我在调用相同函数时使用的控制器(我使用这些没有问题):
CONTROLLER:
$data['for_first_cutoff'] = $this->MyModel->my_function( $date_start_1, $date_end_1);
$data['for_second_cutoff'] = $this->MyModel->my_function( $date_start_2, $date_end_2 );
MODEL:
public function my_function($getDate_start, $getDate_end){
$this->db->select('usr.*, att.id, ss.*');
$this->db->from('usr');
$this->db->join('att', 'att.id = att.id');
$this->db->join('ss', 'ss.id = att.comp');
$this->db->group_by('att.id');
$this->db->where('att_date >=',$getDate_start);
$this->db->where('att_date <=',$getDate_end);
$query = $this->db->get();
return $query->result_array();
}
这是视图(第一个循环)。
<!-- first loop -->
<?php foreach ($for_first_cutoff as $emp_1):?>
<?php
$num_of_days_1 = '12'; //auto computed based on "start1" and "end" dates1.
$salary_cutoff_1 = $emp_1['salary'];
$gross_1 = $salary_cutoff_1 * $num_of_days_1;
?>
<!-- table here-->
| <?=$emp_1['usr_fname'];?> | <?=$gross_1;?> |
<?php endforeach;?>
(第二个循环)相同的内容,但我需要将gross_1减去gross_2才能得到final_gross:
<!-- Second loop -->
<?php foreach ($for_second_cutoff as $emp_2):?>
<?php
$num_of_days_2 = '10'; //auto computed based on "start2" and "end" dates2.
$salary_cutoff_2 = $emp_2['salary'];
$gross_2 = $salary_cutoff_2 * $num_of_days_2;
$final_gross = $gross_1 - $gross_2;
?>
<!-- table here-->
| <?=$emp_2['usr_fname'];?> | <?=$gross_2;?> | <?=$final_gross;?> |
<?php endforeach;?>
HTML 如下所示:
Loop 1
| John Doe | $100 |
| Sarah Doe | $0 |
Loop 2
| John Doe | $50 | $150 |
| Sarah Doe | $2 | $150 | <---- this is wrong. It must be only $2.
我尝试使用此 [post] (How can I get outside foreach loop value in this situation?) 中的方法,但我不知道如何使用我的结构来实现它。
【问题讨论】:
-
这看起来不对:
$final_gross = $gross_1 - $gross_2;这个循环中$gross_1的值是多少?看起来您需要在执行第一个循环时为每个员工存储一组$gross_1值,并检索适当的值以在第二个循环中使用。 -
join
$this->db->join('att', 'att.id = att.id');不起作用-您必须在此处加入用户表中的某些内容-其次,如果 John Doe 出于某种原因在您的一个日期内有两个值,会发生什么情况? -
@kmoser $gross_1 的价值是 $100,$gross_2 是 $50
-
@sintakonte 我正在那里加入其他桌子。那部分工作正常,我对此没有任何问题。我加入 JOIN 的原因只是为了表明我正在加入其他表,而不仅仅是 USR 表。
-
是的,我的第二个问题?
标签: php codeigniter foreach