【问题标题】:how do i access elements of an array in laravel?laravel 中如何访问数组的元素?
【发布时间】:2020-12-30 09:59:23
【问题描述】:

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

{{dd($numberofnotifications)}}

我得到以下信息:

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

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

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

{"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":"John@gmail.com","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"}

【问题讨论】:

  • 您是否在 collection 上添加了循环?它会一一为您提供项目,然后您使用对象表示法访问。
  • 不,我没有。我会用@foreach 来做吗?
  • 是的,那你还在等什么:-)
  • 您想将每个元素的值与什么值进行比较?
  • 我想将每个元素的名称值与登录用户的名称进行比较

标签: arrays laravel laravel-notification


【解决方案1】:

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

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

或者你可以使用foreach循环:

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

【讨论】:

  • 好的,所以我已经设法弄清楚了你的方式,但现在我如何计算有多少等于一个值。这就是我设法用来获取名称值的方法:$notification->data['data']['name'],这就是我比较两者的方式:$notification->data['data'] ['name'] == Auth::user()->name。我如何计算这个回报有多少
  • 然后,使用 where() 和 count() 获取数据: $data = Model::query()->where('your_field', $your_value)->count();
  • 这样的:tr​​ansform($notification->data['data']['name'])
  • 对不起,我弄糊涂了。我在上面编辑了我的评论
  • 像这样:$data = $numberofnotifications->where($notification->data['data']['name'], '==', Auth::user()->name )->计数()。这给了我 5 的计数,这是不正确的元素总数。但是如果我取出 where() 和计数,它会显示所有等于当前用户名的名称值,即 4,这是正确的
【解决方案2】:

由于结果是一个集合,您可以使用它们进行转换

$numberofnotifications->toArray();

【讨论】:

    【解决方案3】:

    您需要使用 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
        }
    
     
    

    【讨论】:

      【解决方案4】:

      你试过了吗

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

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

      如果你想要记录

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

      【讨论】:

        猜你喜欢
        • 2020-02-03
        • 2020-11-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-09-25
        • 2013-04-06
        • 2021-10-06
        相关资源
        最近更新 更多