如何在Laravel中获取集合的键(索引)

时间:2019-05-14 14:27:43

标签: php arrays laravel multidimensional-array chart.js

我正在使用laravel,我有一个收藏夹,里面有一些收藏夹,所以我想获取每个收藏夹的索引

我的收藏就是这样

 Collection {#4415 ▼
  #items: array:14 [▼
    "01" => Collection {#4311 ▶}
    "02" => Collection {#4318 ▶}
    "07" => Collection {#4325 ▶}
    10 => Collection {#4338 ▶}
    12 => Collection {#4345 ▶}
    13 => Collection {#4352 ▶}
    14 => Collection {#4359 ▶}
    18 => Collection {#4366 ▶}
    20 => Collection {#4373 ▶}
    21 => Collection {#4380 ▶}
    25 => Collection {#4387 ▶}
    26 => Collection {#4400 ▶}
    27 => Collection {#4407 ▶}
    31 => Collection {#4414 ▶}
  ]
}

例如,我想获取01 02 03 04 05,它们是一个月中的几天,我想将它们用于图表js

2 个答案:

答案 0 :(得分:3)

您可以使用过滤器收集帮助器。

$result = $yourCollection->filter(function ($value, $key) {
    return in_array($key, ['01', '02', '03', '04', '05']);
});

或者在外部,如果您想传递该数组,

$monthArr =   ['01', '02', '03', '04', '05'];
$result = $yourCollection->filter(function ($value, $key) use($monthArr) 
{
    return in_array($key, $monthArr);
});

编辑

如果您只想获取集合键,

$keys = $yourCollection->keys();
dd($keys);

这里是official documentation的链接。

答案 1 :(得分:1)

如果您只想获取集合的键,则可以使用https://github.com/flutter/flutter/issues/31818