按以字符串开头的子元素过滤数组

时间:2018-11-27 16:15:59

标签: php

当子元素以某个字符串开头时,如何过滤数组?当'name'匹配'bk-'时,这将过滤结果,但是如何更改以'bk-'开头的匹配元素呢?

$starts_with = 'bk-';

$new_facets = array_filter($facets, function ($var) use ($starts_with) {
    return ($var['name'] == $starts_with);
});

2 个答案:

答案 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);

https://3v4l.org/G0bHI

结果:

Array
(
    [0] => Array
        (
            [name] => bk-0001
        )

    [1] => Array
        (
            [name] => bk-0002
        )

)