切换案例循环PHP

时间:2017-08-18 08:18:31

标签: php mysql while-loop switch-statement

我非常沮丧,我尝试了很多方法,但没有找到我的结果。我在表数据库中有这些数据:

|       PartID         |   HasilProduksi  |QtyProduksi|
|----------------------|------------------|-----------|
|  BLAP-FG152-PF-KGX   |   Repair         |    1      |
|  AWDX-FG002-HN-KGX   |   Reject         |   90      |
|  HMXX-FG022-EG-KGX   |   Good           |  100      |
|  ECJX-FG018-AV-MCM   |   Good           |  111      |

我想用结果创建报告:

|                      |    ACTUAL            |
|       PartID         | ---------------------|
|                      |Good | Repair | Reject|
|----------------------|-----|--------|-------|
|  BLAP-FG152-PF-KGX   |  0  |    1   |   0   |
|  AWDX-FG002-HN-KGX   |  0  |    0   |   90  |
|  HMXX-FG022-EG-KGX   | 100 |    0   |   0   |
|  ECJX-FG018-AV-MCM   | 111 |    0   |   0   |

我正在使用 switch case 方法,但结果与我的预期结果不一样。这是我的代码:

$sqlc = "SELECT * FROM $db_dthp WHERE IdBukti='$id_bukti'";
$qc = mysqli_query($conn, $sqlc);
$c = 0; $good=0; $reject=0; $repair=0;
while ($rc = mysqli_fetch_assoc($qc)) {
    switch ($rc['HasilProduksi']) {
      case 'Good':

        $good += (int) $rc['QtyProduksi'];
        $datagood += (int) $rc['QtyProduksi'];
        break;
      case 'Reject':
        $reject += (int) $rc['QtyProduksi'];
        $datareject += (int) $rc['QtyProduksi'];
        break;
      case 'Repair':
        $repair += (int) $rc['QtyProduksi'];
        $datarepair += (int) $rc['QtyProduksi'];
        break;
      default:
        break;
    }
    $c++;
  }
$res['result'][$i]['data'][$b]['hp'][0]['good'] = number_format($good,0,'.','.'); 
$res['result'][$i]['data'][$b]['hp'][0]['reject'] = number_format($reject,0,'.','.'); 
$res['result'][$i]['data'][$b]['hp'][0]['repair'] = number_format($repair,0,'.','.'); 

你能帮助我吗?

2 个答案:

答案 0 :(得分:1)

如果您使用此其他查询,您将拥有您的数据,并且您不需要在php中切换。您将在查询中执行此操作:

$sqlc="SELECT PartID,
    CASE 
        WHEN HasilProduksi='Good' THEN QtyProduksi ELSE 0
    END as Good,
    CASE 
        WHEN HasilProduksi='Repair' THEN QtyProduksi ELSE 0
    END as Repair,
    CASE 
        WHEN HasilProduksi='Reject' THEN QtyProduksi ELSE 0
    END as Reject
FROM $db_dthp WHERE IdBukti='$id_bukti';"

答案 1 :(得分:1)

如果要执行此操作,您可以使用mysql

SELECT PartID,IF(HasilProduksi ='Good',QtyProduksi,0)as 
GOOD,IF(HasilProduksi ='Repair',QtyProduksi,0)as REPAIR,
IF(HasilProduksi ='Reject',QtyProduksi,0)as REJECT FROM 
$db_dthp group by PartID