Foreach循环给出了错误的结果

时间:2017-07-18 07:17:48

标签: php mysql arrays laravel foreach

我的表数据有两个条件price_id =2price_id = 1,数据如下所示。 enter image description here

所以我的条件是weekday_am列值为nullempty0.00 price_id =2我需要在{{1}处取值并且相同的逻辑将适用于列price_id = 1weekday_pmweekend_am。所以我正在做的是我用两个不同的条件写了两个查询,并使用foreach循环检查值。但它给出了错误的结果。

查询代码:

weekend_pm

对于上述查询,我​​发现错误,因为值没有改变它只取$ArrayTier = BundlePrice::where('bundle_id',$id)->where('price_id','=','2')->get(); $ArrayDefault = BundlePrice::where('bundle_id',$id)->where('price_id','=','1')->get(); foreach($ArrayTier as $value) { $bundle_id = $value->bundle_id; $asset_id = $value->asset_id; foreach($ArrayDefault as $v) { if(!empty($value->weekday_am) || ($value->weekday_am != null)) { $weekam = $value->weekday_am; }else{ $weekam = $v->weekday_am; } if(!empty($value->weekday_pm) || ($value->weekday_pm != null)) { $weekpm = $value->weekday_pm; }else{ $weekpm = $v->weekday_pm; } if(!empty($value->weekend_am) || ($value->weekend_am != null)) { $nonweekam = $value->weekend_am; }else{ $nonweekam = $v->weekend_am; } if(!empty($value->weekend_pm) || ($value->weekend_pm != null)) { $nonweekpm = $value->weekend_pm; }else{ $nonweekpm = $v->weekend_pm; } } $primaryArray[] = ['asset_id' => $asset_id,'weekam' => $weekam,'weekpm' => $weekpm,'nonweekam' => $nonweekam,'nonweekpm' => $nonweekpm]; } 的最后一行值

以上代码的结果是:

price_id =1

如果您看到上述内容,则会为少数几个地方重复相同的值。 但期待结果应如下所示:

array:3 [▼
  0 => array:5 [▼
    "asset_id" => 2
    "weekam" => 150.0
    "weekpm" => 320.0
    "nonweekam" => 160.0
    "nonweekpm" => 420.0
  ]
  1 => array:5 [▼
    "asset_id" => 1
    "weekam" => 120.0
    "weekpm" => 180.0
    "nonweekam" => 220.0
    "nonweekpm" => 420.0
  ]
  2 => array:5 [▼
    "asset_id" => 4
    "weekam" => 120.0
    "weekpm" => 320.0
    "nonweekam" => 220.0
    "nonweekpm" => 420.0
  ]
]

有人可以帮我解决这个问题吗?或者请建议我任何mysql查询,可以在单个查询中执行此操作,而不是通过foreach循环。谢谢

1 个答案:

答案 0 :(得分:2)

您已经忘记加入资产ID,因此在循环播放时您会感到胡言乱语。这样做:

$prices = BundlePrice::where('bundle_id',$id)->get()->groupBy("asset_id"); //The group by is done on the collection, not the query: https://laravel.com/docs/5.4/collections#method-groupby
foreach($prices as $bundleprice) {   
    $price = collect($bundleprice)->where("price_id",1)->first();
    $default = collect($bundleprice)->where("price_id",2)->first();
    if (empty($price) && empty($default)) { continue; }
    if (empty($default)) {
        $default = $price;
    }
    $weekam =  !empty($price->weekday_am)?$price->weekday_am:$default->weekday_am;
    $weekpm = !empty($price->weekday_pm)?$price->weekday_pm:$default->weekday_pm;
    $nonweekam = !empty($price->weekend_am)?$price->weekend_am:$default->weekend_am;
    $nonweekpm = !empty($price->weekend_pm)?$price->weekend_pm:$default->weekend_pm;
    $primaryArray[] = ['asset_id' => $default->asset_id,'weekam' => $weekam,'weekpm' => $weekpm,'nonweekam' => $nonweekam,'nonweekpm' => $nonweekpm];        
}

看起来也更清洁。