dongzun9958 2019-02-05 20:24
浏览 322
已采纳

获取Collection内的Object值

I use DataTables as Service from Yajra in my Laravel application.

I have a collection like this :

Collection {#1178
    #items: array:2 [
    0 => array:7 [
      "email" => "user1@example.com"
      "id" => 6
      "emailBlacklisted" => false
      "smsBlacklisted" => false
      "modifiedAt" => "2019-02-05T17:20:17.723+01:00"
      "listIds" => array:2 [
        0 => 2
        1 => 3
      ]
      "attributes" => {#1139
        +"NAME": "Doe"
        +"FIRSTNAME": "John"
      }
    ]
    1 => array:7 [
      "email" => "user2@example.com"
      "id" => 1
      "emailBlacklisted" => false
      "smsBlacklisted" => false
      "modifiedAt" => "2019-02-05T21:12:04.094+01:00"
      "listIds" => array:1 [
        0 => 2
      ]
      "attributes" => {#1143}
    ]
  ]
}

In my blade view I show email value with {{ $email }} -> Simple

I think this is a very easy problem for you ...

But I can't display the value of attributes key. (I want to show the NAME : Doe). -> attributes is an object inside my collection.

Thank you for helping me unlock...

  • 写回答

3条回答 默认 最新

  • dongxili9934 2019-02-06 03:45
    关注

    If I'm understanding correctly, you want to be able to display the key and the value of the attributes.

    If you are utilizing blade, you could try an expanded foreach loop:

    @foreach($attributes as $key => $value)
        {{ $key }}: {{ $value }}
    @endforeach
    

    This assumes that you already have access to the attributes on each individual model, such as $item->email or in this case $item->attributes. If you need to, you can do @foreach($item->attributes as $key => $value) to start it off.


    If you are only looking to display a specific value, use the null-coalesce operator ??.

    $item->attributes['NAME'] ?? ''
    

    You could use this in your logic elsewhere with any expression that might be null:

    // the fallback does not have to be a string
    $person = Person::find($id) ?? Person::first();
    
    // it can be chained
    $value = $parameter ?? $localDefault ?? $globalDefault;
    

    If the NAME is not found, it will fall back to what comes after the ??, which is an empty string in the example above. This is a nice trick to avoid any errors if the attribute doesn't exist. It is doing the same thing as a ternary checking if it is null:

    ($item->attributes['NAME'] !== null) ? $item->attributes['NAME'] : '';
    

    That is obviously messy, so the null-coalesce operator comes in handy!

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100