php - 如何从 foreach 循环中获取变量?
问题描述
我有一个 for each 循环遍历购物车内容。我想获取shop_id
并在另一个查询中使用它。
$cartcontents = Cart::content()->toArray();
foreach ($cartcontents as $cartcontent) {
$shop_id = DB::table('products')->where('id', $cartcontent['id'])->value('shop_id');
break;
}
$shop_number = DB::table('shops')->where('id',$shop_id)->value('phone_number');
echo $shop_number;
我收到一个错误Undefined variable: shop_id
。我不知道为什么相同的代码在函数的另一部分起作用。
解决方案
您的 shop_id 变量超出范围。您的查询行无法访问 shop_id 的值,因为商店 ID 是在不同范围的 foreach 内声明的。要解决此问题,请在 foreach 上方声明 shop_id 以匹配范围。
$shop_id = null;
$cartcontents = Cart::content()->toArray();
foreach ($cartcontents as $cartcontent) {
$shop_id = DB::table('products')->where('id', $cartcontent['id'])->value('shop_id');
break;
}
$shop_number = DB::table('shops')->where('id',$shop_id)->value('phone_number');
echo $shop_number;
推荐阅读
- python - Google Content API custombatch 产品无法正常工作
- php - 在 Foreach 中使用关联数组常量
- python - Python中基于条件的拆分列表
- amazon-web-services - 如何使用 SAM 模板更改 AWS API Gateway 默认响应?
- python - 数据帧和子数据帧之间的余弦相似度
- python - 输出返回生成的表达式而不是列表
- c++ - 为什么这个 Windows 消息循环不处理快捷键/tab 键?
- r - 按条件改变新变量
- javascript - 运行 ts-node-dev 时 ts-node 的“主”条目无效
- perl - Perl Plack 会话资源因错误而暂时不可用