获取一系列项目的最佳方法,如果匹配则设置变量

时间:2013-03-21 20:49:06

标签: php arrays laravel

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

$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'; }
}

2 个答案:

答案 0 :(得分: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;
    }
}

答案 1 :(得分: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++;
}