当子元素以某个字符串开头时,如何过滤数组?当'name'匹配'bk-'时,这将过滤结果,但是如何更改以'bk-'开头的匹配元素呢?
$starts_with = 'bk-';
$new_facets = array_filter($facets, function ($var) use ($starts_with) {
return ($var['name'] == $starts_with);
});
答案 0 :(得分:0)
更改功能逻辑:
$new_facets = array_filter($facets, function ($var) use ($starts_with) {
return (substr($var['name'],0, 3) == $starts_with);
});
答案 1 :(得分:0)
例如substr这样的工作即可完成,例如:
<?php
$starts_with = 'bk-';
$facets = [
['name' => 'bk-0001'],
['name' => 'bk-0002'],
['name' => 'bx-0001']
];
$new_facets = array_filter($facets, function ($var) use ($starts_with) {
return substr($var['name'], 0, strlen($starts_with)) === $starts_with;
});
print_r($new_facets);
结果:
Array
(
[0] => Array
(
[name] => bk-0001
)
[1] => Array
(
[name] => bk-0002
)
)