首页 > 解决方案 > 过滤键/值对的集合。如何访问密钥?

问题描述

我正在通过一组键/值对进行过滤。在过滤时,如何访问密钥?

关键是:

如何返回键以“按钮”开头的字段?

在这种情况下,我只想获取 button 和 button-2 字段。

在此处输入图像描述

$fields = (stuff in picture)

// Pseudocode of what I'm trying to do
$button_fields = collect($fields)->filter(function($field){
    // I imagine getting the key should be something like this?             
    if($field->key->beginsWith('button')) {
         return;
    }
});

标签: phplaravel

解决方案


在大多数收集方法中,第二个参数是$key. 这是可以做到的,因为你循环了一个关联数组,因此键不是索引而是一个值。其次,strings inPHP没有方法,你应该使用 from 的Str帮助Laravel器,它首先采用 haystack 和 needle 两个参数。

$buttonFields = collect($fields)->filter(function($field, $key){            
    if(Str::startsWith($key, 'button')) {
         return;
    }
});

推荐阅读