0

我正在拨打数据库电话并获取订单的所有服务。如果有与订单相关的特定服务,我需要设置一个变量。这就是我目前正在做的事情,它不会起作用,因为一旦我设置了一个变量,下一个项目就会出现并挤压它。它会覆盖之前服务项的正确值。

$services = OrderService::where('order_id','=',$payload['orderId'])->get(['service_id']);
foreach($services as $service){
    //Screen
    if($service->service_id == 4){ $responseArray['lnpScreen'] = '1';}
    else{ $responseArray['lnpScreen'] = '0'; }
    //Screen 2
    if($service->service_id == 5){ $responseArray['tfpScreen'] = '1';}
    else{ $responseArray['tfpScreen'] = '0'; }
    //Screen 3
    if($service->service_id == 6){ $responseArray['didScreen'] = '1';}
    else{ $responseArray['didScreen'] = '0'; }
}
4

2 回答 2

3

这应该工作:

$responseArray['lnpScreen'] = '0';
$responseArray['tfpScreen'] = '0';
$responseArray['didScreen'] = '0';
foreach($services as $service){
    //Screen
    if($service->service_id == 4){ $responseArray['lnpScreen'] = '1';}
    //Screen 2
    if($service->service_id == 5){ $responseArray['tfpScreen'] = '1';}
    //Screen 3
    if($service->service_id == 6){ $responseArray['didScreen'] = '1';}
}

现在他们不会再覆盖彼此了。

或如 powtac 所述:

$responseArray['lnpScreen'] = '0';
$responseArray['tfpScreen'] = '0';
$responseArray['didScreen'] = '0';
foreach($services as $service){
    switch($service->service_id){
        case 4://Screen
          $responseArray['lnpScreen'] = '1';
          break;
        case 5://Screen 2
          $responseArray['tfpScreen'] = '1';
          break;
        case 6://Screen 3
          $responseArray['didScreen'] = '1';
          break;
    }
}
于 2013-03-21T20:53:14.433 回答
0

您正在覆盖,因为$responseArray每次循环时都使用相同的内容。您需要使用多维数组来跟踪每个服务。这样的事情可能会让你开始:

$services = OrderService::where('order_id','=',$payload['orderId'])->get(['service_id']);
$count = 0;
foreach($services as $service){
    //Screen
    if($service->service_id == 4){ $responseArray[$count]['lnpScreen'] = '1';}
    else{ $responseArray[$count]['lnpScreen'] = '0'; }
    //Screen 2
    if($service->service_id == 5){ $responseArray[$count]['tfpScreen'] = '1';}
    else{ $responseArray[$count]['tfpScreen'] = '0'; }
    //Screen 3
    if($service->service_id == 6){ $responseArray[$count]['didScreen'] = '1';}
    else{ $responseArray[$count]['didScreen'] = '0'; }
    $count++;
}
于 2013-03-21T20:52:21.090 回答