首页 > 解决方案 > 如何从 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。我不知道为什么相同的代码在函数的另一部分起作用。

标签: php

解决方案


您的 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;

推荐阅读