php - 过滤键/值对的集合。如何访问密钥?
问题描述
我正在通过一组键/值对进行过滤。在过滤时,如何访问密钥?
关键是:
- 标题
- 身体
- 积极的
- 按钮
- 按钮 2
如何返回键以“按钮”开头的字段?
在这种情况下,我只想获取 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;
}
});
解决方案
在大多数收集方法中,第二个参数是$key
. 这是可以做到的,因为你循环了一个关联数组,因此键不是索引而是一个值。其次,strings inPHP
没有方法,你应该使用 from 的Str
帮助Laravel
器,它首先采用 haystack 和 needle 两个参数。
$buttonFields = collect($fields)->filter(function($field, $key){
if(Str::startsWith($key, 'button')) {
return;
}
});
推荐阅读
- reactjs - 更改 Office-Addins Excel 启动文件
- python - 单击新组件时收到 Angular 类型错误
- automation - Unattend.xml 在新 PC 首次启动时不起作用
- java - 为什么 jaxb 不将此 XML 文档解组为 Java 对象?
- sql - 在 T-SQL FAST 中计算前 1440 行的高低?
- python - 变量仅在运行代码后更新一次 - Discord.py
- python - Python EXE 文件:为什么运行时会出现 ImportError?
- node.js - 使用 Google Drive API、Angular 和 Node JS 上传数据 URI pdf 文件
- wordpress - 打开浏览器的开发者工具如何阻止服务器循环?
- query-string - 页面上没有查询字符串选项的查询字符串