【问题标题】:Php : Laravel - Array push after using eloquent pluck methodPhp : Laravel - 使用 eloquent pluck 方法后的数组推送
【发布时间】:2017-03-07 04:21:41
【问题描述】:

这是我的查询

$RecipientList = Employees::select(DB::Raw('CONCAT(first_name," ",last_name) as employee_name'),'email')->pluck('employee_name','email');

这给了我想要的正确结果,

但是在我执行查询之后,我还有 1 个键 => 值对要推送到结果数组中。

如果我打印当前结果,它是这样的。

Illuminate\Support\Collection Object
(
    [items:protected] => Array
        (
            [punit@*****.com] => Punit Gajjar
            [milan@*****.com] => Milan Gajjar
            [pritesh@*****.com] => Pritesh Modi
            [pratik@*****.com] => Pratik Modi
            [jyoti@*****.com] => Jyotiranjan J..
        )

)

如果我尝试将我的 Key=>valye 对推送到此数组中,它将不起作用。

array_push(array("All"=>"All"),$RecipientList);

需要输出类似的东西

Illuminate\Support\Collection Object
    (
        [items:protected] => Array
            (
                [All] => All
                [milan@*****.com] => Milan Gajjar
                [milan@*****.com] => Milan Gajjar
                [pritesh@*****.com] => Pritesh Modi
                [pratik@*****.com] => Pratik Modi
                [jyoti@*****.com] => Jyotiranjan J..
            )

    )

【问题讨论】:

    标签: php arrays laravel array-push


    【解决方案1】:

    你有Illuminate\Support\Collection 对象而不是数组。你可以这样做

    $RecipientList->push(["All"=>"All"]);
    

    UPD:有prependmethod

    $RecipientList->prepend('All', 'All');
    

    【讨论】:

    • Nope.. 我的结果是 Illuminate\Support\Collection Object ( [items:protected] => Array ( [punit@*****.com] => Punit Gajjar [milan@*****.com] => Milan Gajjar [pritesh@*****.com] => Pritesh Modi [pratik@*****.com] => Pratik Modi [jyoti@*****.com] => Jyotiranjan J.. [0] => Array ( [All] => All ) ) ) 使用您的解决方案后。
    • @PunitGajjar prepend 方法怎么样? $RecipientList->prepend('All', 'All');
    【解决方案2】:

    这是因为 $RecipientList 是 Collection 而不是 Array。

    试试这个

    RecipientList = Employees::select(DB::Raw('CONCAT(first_name," ",last_name) as employee_name'),'email')->pluck('employee_name','email')->toArray();
    

    如果这不起作用,请尝试以下代码

    RecipientList = Employees::select(DB::Raw('CONCAT(first_name," ",last_name) as employee_name'),'email')->get()->pluck('employee_name','email')->toArray();
    

    希望这会对你有所帮助。

    【讨论】:

      猜你喜欢
      • 2016-03-28
      • 1970-01-01
      • 2017-03-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多