Tec*_*mic 1 php arrays each function eloquent
我对 Eloquent 非常陌生,我花了数小时进行搜索,但找不到解决问题的确切方法。
我有以下模型:
use Illuminate\Database\Eloquent\Model as Eloquent;
use Illuminate\Support\Collection;
class Answer extends Eloquent
{
protected $table = 'tbl_answers';
protected $fillable = [
'method',
'thoughts',
'location'
];
public function getMethodsStats()
{
$methods = Answer::selectRaw('*, count(*) AS method_count')- >groupBy('method');
return $methods;
}
}
Run Code Online (Sandbox Code Playgroud)
在我的控制器中,我尝试遍历结果以将结果回显到屏幕上。这有效:
$methods = $app->answer->getMethodsStats();
$methods->each(function($method, $key)
{
echo " --- Method: " . $method->method . " - " . $method->method_count;
});
Run Code Online (Sandbox Code Playgroud)
输出如预期:
-- 方法:折叠 - 3 --- 方法:揉皱 - 2
为了使事情更容易,我想用这些值填充一个数组。一旦完成,这个数组应该可以在 'each' 函数之外访问。
编码:
$methods = $app->answer->getMethodsStats();
$stats = new array();
$methods->each(function($method, $key) use ($stats)
{
$stats[$method->method] = $method->method_count;
});
echo json_encode($stats);
Run Code Online (Sandbox Code Playgroud)
这不符合我的预期。我只是得到一个空数组。
输出:
[]
我知道我错过了一些基本的东西,但我不知道那是什么。
默认情况下,PHP 按值传递函数参数。您传递一个副本的$stats给你的函数。您需要通过引用传递它,以便函数可以修改它。通过&在变量前附加一个来做到这一点,如下所示:
$methods->each(function($method, $key) use (&$stats) { ... });
echo json_encode($stats);
Run Code Online (Sandbox Code Playgroud)
值得一试: