【问题标题】:Accessing items in array shared using Laravel View::share访问使用 Laravel View::share 共享的数组中的项目
【发布时间】:2015-05-07 23:45:36
【问题描述】:

我的路线中有这个(只有在它工作的地方......)

$constants = DB::table('constants')->get();
View::share('constants', $constants);

如果在我的一个观点中我 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'];

如何从 DB 调用中操作我的数组以便能够像这样使用常量变量?

在 Laravel 中有没有办法比在 foreach 中循环并创建数组更简单/更有效?

【问题讨论】:

    标签: php arrays laravel laravel-4


    【解决方案1】:

    假设您的 constants 中只有一行,您应该使用 first() 检索单个记录而不是集合:

    $constants = DB::table('constants')->first();
    

    然后你会得到一个对象,所以你可以使用这个符号来访问属性:

    $business_name = $constants->business_name;
    

    编辑

    对于您的类型值结构,我建议使用lists

    $constants = DB::table('constants')->lists('value', 'type');
    

    这将创建一个像这样的数组:

    [
        'business_name' => 'Project Framework',
        'foo_type' => 'bar_value'
    ]
    

    用法

    $business_name = $constants['business_name'];
    

    【讨论】:

    • 啊,是的,对不起,我读得不够好。看看我更新的答案
    • 完美,以前从未见过列表项。谢谢。
    猜你喜欢
    • 2019-07-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多