如何传递变量“$ TID,$ ID”为原料的功能?(how to pass variables “$

2019-10-21 22:58发布

当我打电话$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;
}
?>

Answer 1:

它会是不错的散装此外,这样你只需要创建数组并把它传递。

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

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

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


Answer 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关键字 :

$foo = true;

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


文章来源: how to pass variables “$tid, $id” into raw function?