【问题标题】:Remove all elements of an associative array if they have the a specific word in the key [duplicate]如果关联数组的键中有特定单词,则删除它们的所有元素[重复]
【发布时间】:2017-11-21 18:38:56
【问题描述】:

如果键中有一个“TB1”的子字符串,我想删除关联数组的所有元素。

我的数组看起来像:

$output= [
       'TB1_course' => 'required'
       'TB1_session' => 'required'
       'TB2_course' => 'required'
    ]

我想删除 TB1_course 和 TB1_session,所以我的最终数组如下所示:

$output =[
   'TB2_course' => 'required
]

有没有什么方法可以简单明了地做到这一点?

我最初的猜测是为每个循环使用一个:

foreach ($output as $key =>$value){
//remove
}

感谢大家的帮助!

【问题讨论】:

标签: php arrays associative-array


【解决方案1】:

按键过滤数组:

$input = [
    'TB1_course' => 'required',
    'TB1_session' => 'required',
    'TB2_course' => 'required',
];

$filter = function ($key) {
    return substr($key, 0, 4) === 'TB2_';
};

$output = array_filter($input, $filter, ARRAY_FILTER_USE_KEY);

var_dump($output);

输出:

array(1) {
  'TB2_course' =>
  string(8) "required"
}

请参阅 http://php.net/array_filter 以获取对过滤数组有用的 array_filter 函数的文档。

【讨论】:

  • 完美运行,谢谢!
猜你喜欢
  • 2020-05-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-12
  • 1970-01-01
  • 2020-05-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多