【问题标题】:Laravel : Removing an element from a collection arrayLaravel:从集合数组中删除元素
【发布时间】:2017-08-23 20:14:53
【问题描述】:

我使用一个名为 $users 的变量来“提取”我的用户表中的电子邮件,使用:

$users = user::all()->pluck('email');

当我 dd($users) 时,我得到了这个

<pre>
Collection {#214 ▼
  #items: array:8 [▼
    0 => "adminone@example.com"
    1 => "admintwo@example.com"
    2 => "Adobot@example.com"
    3 => "Lawly@example.com"
    4 => "Cerms@example.com"
    5 => "Charlie@example.com"
    6 => "test@example.com"
    7 => "test001@example.com"
  ]
}
</pre>

这意味着 $users 不是纯粹的数组,当我将它视为数组时会遇到各种类型的错误。

我的问题是,在 php 中(在 Laravel 框架中)我如何从上面的变量中删除特定用户的电子邮件?还是有更好的方法来使用“pluck”以便它返回一个数组?

提前致谢。

【问题讨论】:

    标签: php arrays laravel collections


    【解决方案1】:

    我也遇到了这个问题,我是这样解决的:

    DB::table('user')-&gt;pluck('email')-&gt;all();

    【讨论】:

    • 这是我正在寻找的解决方案,因为上面的代码返回一个数组而不是一个标准类对象,批准!
    【解决方案2】:

    这里$users 是一个标准类对象,您可以对其进行迭代并将其属性推送到一个数组,例如:

    $userDetails = array();
    foreach($users as $user)
    {
      $userDetails[] = (array)$user;
      // or
      $userDetails[] = $user->index;
    }
    

    您也可以在foreach() 中放置一个If 块来检查某些情况。

    【讨论】:

    • 如果我理解正确,我们使用 foreach() 来访问 Std 类对象内部的数组(循环一次),然后将整个数组移动到 $userDetails?感谢您的快速回复!
    • Kevin:foreach() 需要遍历 Std Class 对象的所有属性。迭代后,如果你想要数组中的数据,则将其推送到数组变量中,否则不要。
    【解决方案3】:

    你会想使用-&gt;forget()

    $collection->forget($key);
    

    或者你可以使用reject方法

    $newColection = $collection->reject(function($element) {
        return $element === 'emailaddress@';
    });
    

    【讨论】:

      【解决方案4】:

      如果您想删除电子邮件 ID 为 0 的电子邮件,请先按照以下查询进行操作

         $users = user::all()->pluck('email');
         unset($users['0']);
         $dd($users);
      

      【讨论】:

      • 我不想从我的数据库中永久删除电子邮件,只需从 $users 变量中删除“Lawly@example.com”即可。
      • 类似地,您从集合中删除其他索引
      猜你喜欢
      • 2011-02-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-04
      • 2012-05-13
      • 1970-01-01
      相关资源
      最近更新 更多