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 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 R语言卸载之后无法重装,显示电脑存在下载某些较大二进制文件行为,怎么办
  • ¥15 java 的protected权限 ,问题在注释里