我的 route 有这个(只有它起作用的地方......)
$constants = DB::table('constants')->get();
View::share('constants', $constants);
如果在我的一个 View 中我使用 var_dump 常量,我会得到以下结果:
array(1) { [0]=> object(stdClass)#129 (3) { ["id"]=> string(1) "1" ["type"]=> string(13) "business_name" ["value"]=> string(17) "Project Framework" } }
然后我想做:
$business_name = $constants->business_name;
or
$business_name = $constants['business_name'];
如何从数据库调用中操作我的数组,以便能够像这样使用常量变量?
Laravel 中有没有一种方法可以比在 foreach 中循环并创建数组更简单/更高效?
最佳答案
假设您的常量
中只有一行,您应该使用first()
来检索单个记录而不是集合:
$constants = DB::table('constants')->first();
然后您将获得一个对象,以便您可以使用此表示法来访问属性:
$business_name = $constants->business_name;
编辑
对于您的类型值结构,我建议使用列表
:
$constants = DB::table('constants')->lists('value', 'type');
这将创建一个像这样的数组:
[
'business_name' => 'Project Framework',
'foo_type' => 'bar_value'
]
使用
$business_name = $constants['business_name'];
关于php - 使用 Laravel View::share 访问共享数组中的项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28897633/