gpt4 book ai didi

php - 检查值时避免循环

转载 作者:行者123 更新时间:2023-11-30 22:14:18 25 4
gpt4 key购买 nike

我有监视列表。用户可以将产品添加到关注列表。这样就填充了 user_id 和 product_id。

id   user_id  product_id
1 1 3
2 1 4
3 1 5
4 2 3
5 2 4
.. .. ..

如果只有该产品还不在该用户的监视列表中,我希望有“将产品添加到监视列表”按钮。否则,“从监视列表中删除产品”按钮。这就是我在 Controller 中的内容。

 public function index()
{
$products=Product::where(['status'=>'On sale'])->get();
$check=Watchlist::where(['user_id'=>Auth::user()->id])->get();
return View('product.index',['products'=>$products,'check'=>$check]);
}

在 View 中:如果我执行以下操作,由于该循环,按钮出现的次数与监视列表表中 user_id 的次数一样多。但我需要循环来检查用户的所有 product_id。

  <?php foreach($products as $product):?>
<?php foreach($check as $che):?>
<?php
if($che->product_id==$product->product_id)
{
?><a href="" class="removewatchlist" data-id="<?php echo $product->product_id;?>"><button class="btn btn-info">Remove from watchlist</button></a> <?php
}
else
{
?><a href="" class="watchlist" data-id="<?php echo $product->product_id;?>"><button class="btn btn-info">Add to watchlist</button></a> <?php
}

?>
<?php endforeach;?>
<?php endforeach;?>

最佳答案

您可以简单地创建一个数组,其中包含 Controller 中监视列表中的所有产品 ID,例如:

$chraw = Watchlist::where(['user_id'=>Auth::user()->id])->get();
$check = array();
foreach($checkb as $che)
$check[] = $che->product_id;

然后在 View 中简单地检查 id 是否在数组中:

<?php foreach($products as $product): ?>
<?php if(in_array($product->product_id, $check)): ?>
...

关于php - 检查值时避免循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38976788/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com