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

如何用PHP从多维数组中获取子数组或指定键对应值

PHP 从多维数组中按键取值的实现方案

我来帮你搞定这个需求!咱们可以写一个灵活的函数,既能处理多维数组的递归查找,也能支持仅当前层级的查找,完全匹配你要的逻辑:找到键对应的值,非数组类型直接返回,数组类型就返回整个子数组。

方案一:递归遍历整个多维数组(推荐)

如果你的目标键可能出现在数组的任意层级,这个递归函数会帮你自动深入查找:

function getValueByKey($array, $targetKey) {
    foreach ($array as $key => $value) {
        // 找到目标键,直接返回对应值(不管是数组还是普通类型)
        if ($key === $targetKey) {
            return $value;
        }
        // 如果当前值是数组,递归继续查找
        if (is_array($value)) {
            $result = getValueByKey($value, $targetKey);
            // 递归找到结果就返回,没找到就继续遍历
            if ($result !== null) {
                return $result;
            }
        }
    }
    // 没找到目标键时返回默认值,可根据需求修改为false/空字符串等
    return null;
}

函数说明

  • 接收两个参数:待遍历的多维数组$array,以及要查找的目标键$targetKey
  • 遍历数组的每一项,匹配到目标键后直接返回对应值——完全符合你“非数组返回值、数组返回子数组”的要求
  • 如果当前值是子数组,就递归调用自身继续查找,一旦找到结果就向上返回
  • 遍历完整个数组都没找到目标键时,返回null(你可以改成自己需要的默认值)

用你的示例数组测试

假设你的完整示例数组是这样的:

$category = array(
    'Account' => array(
        'Show Balance' => array(
            'Recharge' => 2300,
            'Success' => 12000,
            'Failure' => 250
        ),
        'Transaction History' => 'Available'
    ),
    'Settings' => array(
        'Profile' => 'Edit',
        'Security' => array(
            'Two-Factor' => 'Enabled'
        )
    )
);

测试几个场景:

  1. 查找对应值为普通类型的键:
echo getValueByKey($category, 'Recharge'); // 输出:2300
echo getValueByKey($category, 'Transaction History'); // 输出:Available
  1. 查找对应值为子数组的键:
$showBalanceData = getValueByKey($category, 'Show Balance');
print_r($showBalanceData);
// 输出:
// Array
// (
//     [Recharge] => 2300
//     [Success] => 12000
//     [Failure] => 250
// )
  1. 查找不存在的键:
var_dump(getValueByKey($category, 'NonExistentKey')); // 输出:NULL

方案二:仅查找当前层级的键

如果你的需求是只在数组的直接层级查找(不深入子数组),那函数可以更简单:

function getValueByCurrentLevel($array, $targetKey) {
    // 检查当前层级是否存在目标键
    if (array_key_exists($targetKey, $array)) {
        return $array[$targetKey];
    }
    return null;
}

比如调用getValueByCurrentLevel($category, 'Account')会返回Account对应的子数组,但调用getValueByCurrentLevel($category, 'Recharge')会返回null,因为Recharge不在$category的直接层级里。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 11:11:48