我如何访问laravel中数组的元素?

问题描述

我正在尝试计算等于某个值的元素的数量,但是当我运行时,我很难找到我想要比较的元素:

{{dd($numberofnotifications)}}

我得到以下信息:

enter image description here

但我需要比较的值在“属性”下

那么我如何获得属性下的值?

当我打印出数组的每个元素时,我得到以下格式:

{"id":"96a40ebb-a2d1-44d8-9600-e94dd026f152","type":"App\\Notifications\\CommentCreated","notifiable_type":"App\\User","notifiable_id":1,"data":{"comment_id":9,"data":{"name":"John","date":"2020-12-30T08:37:47.000000Z","email":"[email protected]","post":2,"body":"test"},"message":"John commented on your post"},"read_at":null,"created_at":"2020-12-30T08:37:47.000000Z","updated_at":"2020-12-30T08:37:47.000000Z"}

解决方法

由于结果是一个集合,您可以使用

转换它们
$numberofnotifications->toArray();
,

您需要使用 foreach 来遍历集合:

foreach($numberofnotification as $number)
    {
        $number->name;   //name here is the "name" of the attribute you want to access
    }

如果要将它们存储在数组中,则:

foreach($numberofnotification as $number)
    {
       $attributes[]=$number->name;   //name here is the "name" of the attribute you want to access
    }

 
,

你试过了吗

//认为$username是登录的用户名

$filtered_count = $numberofnotifications->where('name',$username)->count();

如果你想要记录

$filtered = $numberofnotifications->where('name',$username)->all();
,

这些项目似乎是一个 DatabaseNotifications 数组。因此,您可以通过索引手动获取每个元素:

$numberofnotifications[0]->id;
// or
$numberofnotifications[0]->type

或者你可以使用 foreach 循环:

foreach ($numberofnotifications as $notification) {
    $notification->id;
}