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.

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

报告相同问题?

悬赏问题

  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统