Laravel - > get()返回null

时间:2016-08-29 22:11:10

标签: php laravel laravel-5.3

我在Laravel 5.3中有一个我在查询后创建的集合,这个dd()只是一个项目,不想垃圾邮件太多......

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: []
    }
  ]
}

编辑#1:

以下是$calls->toJSON()输出:

[
    {
        "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
    }
]

问题是,当我尝试做的时候:

    $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++;
    }

如果我没有设置默认值,$response中的每个值都会0null。值存在,它们在集合中,并且正确格式化,但无论出于何种原因,我无法得到它们。有什么我想念的吗?

当前文档:

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

编辑#2:

在@Andrej Ludinovskov的帮助下找到了答案并得到了正确答案:

$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++;
}

1 个答案:

答案 0 :(得分:0)

你有元素集合,它的键从0到n开始。关键的电话'是这个系列的一个项目的关键。所以你的代码应该是这样的:

$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++;

}