如果关联数组中包含特定单词

时间:2017-06-19 13:48:19

标签: php arrays associative-array

如果密钥在密钥中的子字符串为“TB1”,我想删除关联数组的所有元素。

我的数组看起来像:

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

我想删除TB1_course和TB1_session,以便我的最终数组看起来像:

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

有没有办法以简洁的方式做到这一点?

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

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

感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

Filter the array by key:

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

Output:

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

See http://php.net/array_filter for the documentation of the array_filter function that is useful to filter arrays.

相关问题