如何将变量“$tid,$id”传递给原始函数?

how to pass variables "$tid, $id" into raw function?

当我在原始函数中调用 $id$tid 以从 mongodb 集合的子文档中获取一些数据时,它显示错误 these two variables are undefined($tid,$id)

<?php
$id=IntValue;
$tId=IntValue;
if($tId==0)
{
    $maxPlayers=0;
}
else
{
  $result = DB::collection('PrizeDistributionTemplate')->raw(function($collection)
        {

            return $collection->aggregate(array(
                array(
                    '$match' => array( 'id' => $id,'templates.tId' => $tid)
                ),
                array( '$unwind' => '$templates' ),
                array(
                    '$match' => array( 'id' => $id,'templates.tId' => $tid)
                ),
            ));       
        });

  $result=json_decode(json_encode($result),true);
  $maxPlayers=$result['result'][0]['templates']['maxPlayers'];
  $maxPlayers=intval($maxPlayers)+2;
}
?>

当您在 PHP 中使用回调函数时,该函数拥有自己的作用域,无法从其作用域外访问变量。

$foo = true;

DB::collection('something')->raw(function ($collection) {
    echo $foo;// $foo is undefined here, this create an error
});

echo $foo;// here it work

但是您可以使用 PHP use keyword:

为回调提供变量
$foo = true;

DB::collection('something')->raw(function ($collection) use ($foo) {
    echo $foo;// now it works
});

批量加法效果很好,这样你只需要在数组上创建并传递它。

$temp = [
   [
     'item' => "envelopes"
   ],
   [
     'item' => "envelopesas"
   ],
   [
     'item' => "lala"
   ]
 ];

 $userData = DB::table('log') - > raw(function ($collection) use($temp) 
 {

   return $collection - > insertMany($temp);
 });