duancan1950 2018-04-20 07:51
浏览 98
已采纳

未定义的索引 - isset guard不适用于帮助程序

I have a multi-dimensional array coming from post request. It looks like this: $request['bags'][1]['fruits']. Sometimes, this value doesn't exist so it returns Undefined Index error.

$model->fruits = $request['bags'][1]['fruits'];

If I use an isset guard in my controller, it works:

$model->fruits = isset($request['bags'][1]['fruits'];) ? $request['bags'][1]['fruits'] : '';
$model->save();

Now, I wanted to wrap this in a function, so that I can use something like nullable($fruits) to make this work.


Now, I tried to wrap this inside a helper method; so I created Helper.php and added this method inside:

function nullable($value) {
    return (isset($value)) ? $value : '';
}

But in my controller, when I call nullable(), it throws Undefined Index error.

nullable($request['bags'][1]['fruits']); // Undefined Index

isset($request['bags'][1]['fruits']) ? $request['bags'][1]['fruits'] : ''; // works
  • 写回答

2条回答 默认 最新

  • dpnof28482 2018-04-20 07:59
    关注

    The problem you encounter is, that the Undefined Index Notice is thrown as soon as the undefined index is requested. This happens as soon as you want to access the value behind the key upon calling your helper function with nullable($request['bags'][1]['fruits']). The value is extracted and then send to the function.

    What you can do instead, is using the null coalesce operator ?? in PHP.

    $model->fruits = $request['bags'][1]['fruits'] ?? '';
    

    If you really want to create your own helper function though, you need to do it in a way, in wich the field is not accessed when the parameters are transfered to the function.

    This can be accomplished by spearating the array from the keys you want to access.

    function nullable(array $array, ...$keys) {
        $current = $array;
        foreach($keys as $key) {
            if (!isset($current[$key])) {
                return NULL;
            }
            $current = $current[$key];
        }
        return $current;
    }
    

    A call would then be nullable($request, 'bags', 1, 'fruits');

    Code example

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?
  • ¥15 matlab(相关搜索:紧聚焦)