1

I have a collection in Laravel 5.3 that I created after a query, this dd() is just one item, didn't want to spam to much...

Collection {#950
  #items: array:1 [
    0 => Callrail {#942
      #table: "callrails"
      #appends: []
      #with: []
      #hidden: []
      #casts: []
      #connection: null
      #primaryKey: "id"
      #keyType: "int"
      #perPage: 15
      +incrementing: true
      +timestamps: true
      #attributes: array:2 [
        "hourofday" => 1
        "calls" => 2
      ]
      #original: array:2 [
        "hourofday" => 1
        "calls" => 2
      ]
      #relations: []
      #visible: []
      #fillable: []
      #guarded: []
      #dates: []
      #dateFormat: null
      #touches: []
      #observables: []
      +exists: true
      +wasRecentlyCreated: false
      #forceDeleting: false
      -originalData: []
      -updatedData: []
      -updating: false
      -dontKeep: []
      -doKeep: []
      #dirtyData: []
    }
  ]
}

EDIT #1:

Here is the $calls->toJSON() output:

[
    {
        "hourofday":1,
        "calls":2
    },
    {
        "hourofday":15,
        "calls":1
    },
    {
        "hourofday":16,
        "calls":4
    },
    {
        "hourofday":18,
        "calls":7
    },
    {
        "hourofday":19,
        "calls":2
    },
    {
        "hourofday":20,
        "calls":1
    },
    {
        "hourofday":22,
        "calls":2
    }
]

The problem is, when I try to do:

    $i = 0;
    while($i != 24) {
        $response[]  = array(
            'name' => date('g A', strtotime('2016-01-01 '.$i.':00:00')), 
            'y' => $calls->whereStrict('hourofday', $i)->get('calls', 0);
        );
        $i++;
    }

Every value in the $response always has 0, or null if I don't put a default value in. The values exist, they are in the collection, and are properly formatted, but for whatever reason I can't get them. Is there something I am missing?

Current Documentation:

https://www.laravel.com/docs/5.3/collections#method-get

EDIT #2:

Found the answer with help from @Andrej Ludinovskov and the correct answer:

$i = 0;
while($i != 24) {
    // You have to get the first item in the array, then you can use it like normal
    $callCount = $calls->whereStrict('hourofday', $i)->first(); 
    $response[]  = array(
        'name' => date('g A', strtotime('2016-01-01 '.$i.':00:00')),
        'y' => ($callCount?$callCount->calls:0)
    );
    $i++;
}
4

1 回答 1

0

你有元素的集合,它有从 0 到 n 的键。键 'calls' 是这个集合的一个项目的键。所以你的代码应该是这样的:

$i = 0;
while($i != 24) {
    $item = $calls->whereStrict('hourofday', $i)->get(0, null);
    $cnt = 0;
    if ($item != null) {
        $cnt = $item->calls
    }
    $response[]  = array(
            'name' => date('g A', strtotime('2016-01-01 '.$i.':00:00')), 
            'y' => $cnt
        );
    $i++;

}

于 2016-08-29T22:19:21.067 回答