Laravel集合从每个函数检索变量结果 [英] Laravel collection retrieve variable result from each function

查看:64
本文介绍了Laravel集合从每个函数检索变量结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从数据库中检索了一个laravel集合,我希望基于三个计算在该数据库上更新某些值.但是在进行计算之前,我首先要检查所有相关的收集项目是否不为空.我可以检查它们是否为null,但由于某种原因不能恢复具有Controller功能范围的错误变量,以告知用户尚未设置变量.

I retrieve a laravel collection from a database on which I want to update certain values based on three calculations. But before I do the calculations I first check if all the relevant collection items is not null. I can check if they are null but for some reason cannot rerieve an error variable that has Controller function scope to tell a user that a variable has not been set.

$error_arr = [];
$calculation = FertilApp::calculation($product, $farm, $agent);
$calculation->each(function ($item, $key) {
    if ($item->ha === null) {
        $error_arr[] = 'Prices has been updated';
        $error_arr[] = 'But no calculation has been done, please update following block:' . $item->block;
        return false;
     }
});

即使我知道 ha 键为 null ,变量 $ error_arr 仍返回一个空数组.另一种方法是使用普通的 foreach()循环.我已经尝试过了,并且可以使用,但是我真的很想知道为什么它不起作用.

The variable $error_arr returns an empty array even though I know the ha key is null. The alternative is to use a normal foreach() loop. I have tried it and it works, but I really want to know why this is not working.

有人可以帮忙给我一个线索,为什么这个集合 each()方法拒绝我从集合方法外部访问变量的值?

Can someone please help to give me a clue to why this collection each() method is denying my variable access to values from outside the collection method?

如果我尝试将变量作为参数传递,则会收到以下错误消息不能将标量值用作数组.

If I try to pass my variable as a parameter I get the following error message Cannot use a scalar value as an array.

Laravel版本:5.6.39

推荐答案

尝试使用 global 语句:

$calculation->each(function ($item, $key) {
   global $error_arr;

$ error_arr 在您的代码中为空,因为它不存在于 each 方法的回调 function 的范围内.与其他语言(例如JavaScript)不同,默认情况下,函数内部无法访问函数外部的变量.有关详细信息,请参见有关可变范围的PHP文档.

$error_arr is empty in your code, because it doesn't exist in the scope of the callback function of your each method. Unlike other languages – like JavaScript – variables outside a function aren't accessible by default inside the function. See PHP's documentation on variable scope for details.

这篇关于Laravel集合从每个函数检索变量结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆