doudu5029 2017-03-04 23:08
浏览 53
已采纳

如何回显Collection数组中的变量?

I get some data from Controller and pass it to View with

// Foreach url get latest 2 Analytics data - This isn't my code but it works
$urls = URL::with('analytics')->get()->map(function($urls) {
        $urls->analytics = $urls->analytics->sortByDesc('created_at')->take(2);
        return $urls;
    });
return view('urls.index')->with('urls', $urls); 

In index view I did this

@foreach ($urls as $url)
<?php dd($url->analytics); ?>
@endforeach

so I get a Collection of some sort which is new to me.

Collection {#422 ▼
  #items: array:2 [▼
    12 => Analytic {#2076 ▶}
    11 => Analytic {#1951 ▼
      #table: "analytics"
      #connection: null
      #primaryKey: "id"
      #keyType: "int"
      #perPage: 15
      +incrementing: true
      +timestamps: true
      #attributes: array:5 [▼
        "id" => 990
        "quality" => 1
        "url_id" => 23
        "created_at" => "2017-02-20 07:00:02"
        "updated_at" => "2017-02-20 07:00:02"
      ]
      #original: array:5 [▶]
      #relations: []
      #hidden: []
      #visible: []
      #appends: []
      #fillable: []
      #guarded: array:1 [▶]
      #dates: []
      #dateFormat: null
      #casts: []
      #touches: []
      #observables: []
      #with: []
      +exists: true
      +wasRecentlyCreated: false
    }
  ]
}

How do I get the values of each Analytic? I believe I need something like

$url->analytics->(enter_collection)[array_index]['Analytic']['quality'];

I always get two last Analytic values with each url so I would like to compare them

  • 写回答

1条回答 默认 最新

  • dqwh0108 2017-03-05 00:21
    关注

    Looks like you need to give a good look over the Collections documentation! In your particular case, since you are only working with 2 of these, you can do something like:

    $url->analytics->first()->quality
    $url->analytics->last()->quality
    

    However, collections do implement ArrayAccess, so you also have the opportunity to do something like $url->analytics[index]->quality.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 vscode问题请教
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类
  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM