Laravel 5.7中的Arr :: get()与data_get() [英] Arr::get() vs data_get() in Laravel 5.7

查看:1937
本文介绍了Laravel 5.7中的Arr :: get()与data_get()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 data_get()辅助函数,我们可以使用点获得嵌套数组的值。表示法如下:

With data_get() helper function, we can get value of a nested array using dot . notation as following:

$my_arr = [
    'a' => ['lower' => 'aa', 'upper' => 'AAA',], 
    'b' => ['lower' => 'bbb', 'upper' => 'BBBBB',],
];

因此,我可以将 a 降低

data_get($my_arr, 'a.lower');

您还可以执行以下操作。

And you also do the following.

Arr::get('a.lower');

以防万一,我只想获取数组的第一级。我可以同时做这两个事情:

In case I just want to get only the first level of the array. I just can do both:

data_get($my_arr, 'a');

OR

Arr::get($my_arr, 'a');

您推荐我哪个,为什么?我只想继续改善Laravel的经验,并从高级开发人员那里获得好的建议,以选择当前最佳的选择。

Which one do you recommend me and why? I just want to keep improving my Laravel experience and get good advice from senior developers to choose the best options at the moment.

推荐答案

要根据上下文来决定使用哪个。

It depends on the context to decide which one to use.

如果需要在索引中使用通配符,则必须使用 data_get 作为 Arr :: get 不支持通配符。

If you need to use wildcard in your index, you have to go with data_get as Arr::get does not support wildcards.

示例:

Arr::get($my_arr, '*.lower'); // null
data_get($my_arr, '*.lower'); // ["aa", "bbb"]



2。变量类型



Arr :: get 只是假设您的变量是数组。因此,如果使用对象,则必须使用 data_get 。但是,如果您确定变量是数组并且不需要通配符,则应继续使用 Arr :: get 来避免 data_get 进行评估,以查看您的变量是对象还是数组。

2. Variable Type

Arr::get simply assumes that your variable is an array. Therefore, if you use an object, you have to go with data_get. If, however you are sure your variable is an array and you don't need wildcards, you should proceed with Arr::get to avoid unnecessary checks from data_get that evaluates to see if your variable is an object or array.

这篇关于Laravel 5.7中的Arr :: get()与data_get()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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