循环不会在表列中重复值

时间:2017-01-10 02:45:18

标签: php mysql loops foreach

如果标题写得不好,我很抱歉,因为我不确定这究竟叫做什么!

我有一个非常基本的表设置:employees和employees_deductions。我想加入这两个并使用php在表中显示内容。

我找到了员工:

$employees = $wpdb->get_results("SELECT * from employees");

然后循环遍历$employees,在每一个上,我得到扣除,然后在表格中显示:(简化下面的代码)

foreach($employees as $emp) {
  $deductions = $wpdb->get_results("SELECT * FROM employee_deductions WHERE employee_id = $this_employee_id");

  foreach($deductions as $ded) {
    <tr>
       <td>name</td>
       <td>deduction</td>
    </tr>
  }

}

我的问题是如果第一个单元格在BLANK上面包含“name”,如果它上面的行中的单元格包含相同的“名称”?

我得到了什么:

+------+-----------+
| name | deduction |
+------+-----------+
| John |       100 |
| John |       142 |
| John |       204 |
| Mary |       200 |
| Mary |       340 |
+------+-----------+

期望的结果:

+------+-----------+
| name | deduction |
+------+-----------+
| John |       100 |
|      |       142 |
|      |       204 |
| Mary |       200 |
|      |       340 |
+------+-----------+

2 个答案:

答案 0 :(得分:1)

您可以在一个额外的变量中存储姓氏或ID,然后将其与当前名称/ ID进行比较。如果匹配,则只显示一个空列,如果不匹配,则显示名称。

假设您的SELECT查询按名称排序,这是可行的:

foreach($employees as $emp) {

    $lastid = ''; /* WHERE YOU WILL STORE THE LAST ID OR NAME; JUST LEAVE IT EMPTY AT FIRST */

    $deductions = $wpdb->get_results("SELECT * FROM employee_deductions WHERE employee_id = $this_employee_id");

    foreach($deductions as $ded) {
        echo '<tr>';
        // JUST REPLACE THE CORRESPONDING VARIABLE/CONDITION BELOW
        echo (empty($lastid) || $lastid != $this_employee_id)?'<td>name</td>':'<td></td>';
        echo '<td>deduction</td>
              </tr>';

        $lastid = $this_employee_id; /* STORE THE CURRENT ID/NAME TO THIS VARIABLE */

    }

}

答案 1 :(得分:0)

我想你的代码运行正确, 我会这样做

foreach($employees as $emp) {
  $deductions = $wpdb->get_results("SELECT * FROM employee_deductions WHERE employee_id = $this_employee_id");

  //becasue same employee_id must have same name
  $show = 0;
  foreach($deductions as $ded) {
    <tr>
       if ($show == 0) {
         <td>name</td>
       } else {
         <td></td>
       }
       <td>deduction</td>
    </tr>
    $show++;
  }

}