You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在多维数组中获取以指定字符串开头的数组键

多维数组匹配指定前缀键的实现方法

可以通过递归遍历多维数组的每一层,逐层筛选符合前缀要求的键,同时递归处理嵌套的子数组,就能拿到所有层级符合条件的键。

完整实现代码

function getKeysByPrefix(array $array, string $prefix): array
{
    $result = [];
    foreach ($array as $key => $value) {
        // 匹配当前层的键前缀
        if (str_starts_with($key, $prefix)) {
            $result[] = $key;
        }
        // 递归处理嵌套子数组
        if (is_array($value)) {
            $result = array_merge($result, getKeysByPrefix($value, $prefix));
        }
    }
    return $result;
}

如果你的PHP版本低于8.0(无内置str_starts_with函数),可以把前缀匹配逻辑替换为以下写法:

if (substr($key, 0, strlen($prefix)) === $prefix) {
    $result[] = $key;
}

调用示例

修正原示例数组的语法笔误后调用函数:

$arr = array(
    'first-key' => 'first value',
    'second-key' => 'second value',
    array(
        'foo-1' => 'val',
        'bar'=> 'value',
        'foo-2' => 'val2'
    )
);

$matchedKeys = getKeysByPrefix($arr, 'foo-');
print_r($matchedKeys);

输出结果

Array
(
    [0] => foo-1
    [1] => foo-2
)

如果需要同时拿到键对应的值,只需把存储逻辑$result[] = $key修改为$result[$key] = $value即可。

内容的提问来源于stack exchange,提问作者Louis__

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 05:27:02