0

我在 codeigniter 下使用 PHP 有两 (2) 个 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] 中找到的方法(在这种情况下如何获得 foreach 循环值之外的值?),但我不知道如何使用我的结构来实现它。

4

1 回答 1

1

好的 - 根据评论,您可以尝试以下操作

创建一个数组来保存第一个循环中的数据 - 我用作键att.id(应该可能是你的 user_id) - 并从你的第一个循环访问这个数组,你的 id 来自第二个循环

<!-- first loop -->
<?php 
    $arrGrossData = [];
    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; 
   $arrGrossData[$emp_1['att.id']] = $gross_1;
?>

   <!-- table here-->
   | <?=$emp_1['usr_fname'];?> | <?=$gross_1;?> |


<?php endforeach;?>


<!-- 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 = (isset($arrGrossData[$emp_2['att.id']])) ? $arrGrossData[$emp_2['att.id']] - $gross_2 : $gross_2;
?>

   <!-- table here-->
  | <?=$emp_2['usr_fname'];?> | <?=$gross_2;?> | <?=$final_gross;?> |


<?php endforeach;?>
于 2020-05-29T06:53:23.253 回答