Home >Backend Development >PHP Tutorial >How to use code to recursively obtain the value of a specified key in an array through PHP

How to use code to recursively obtain the value of a specified key in an array through PHP

jacklove
jackloveOriginal
2018-06-08 14:33:244263browse

In PHP, we often encounter the need to obtain the key value in an array, so this article will explain the relevant knowledge.

/**
 * 递归获取一个数组中指定key的值
 * @param $array
 * @param $keys
 * @param string $delimiter
 * @return mixed
 */
function get_deep_value($array, $keys, $delimiter = '.')
{
    $keys = explode($delimiter, $keys);
    $key = array_shift($keys);
    if (sizeof($keys) > 0 && isset($array[$key])) {
        return get_deep_value($array[$key], implode($delimiter, $keys), $delimiter);
    } else {
        return $array[$key] ?? null;
    }
}
 
$a = [
    'a' => [
        'b' => 'error',
        'c' => [
            'd' => [
                'e' => [
                    'f' => 'ok',
                ]
            ]
        ]
    ]
]; 
var_dump(get_deep_value($a, 'a.c.d.e.f'));
/**
 * 输出:
 * string(2) "ok"
 */
var_dump(get_deep_value($a, 'a.b'));
/**
 * 输出:
 * string(5) "error"
 */
var_dump(get_deep_value($a, 'a.b.c'));
/**
 * 输出:
 * NULL
 */

This article lists the relevant methods of recursively obtaining the value of a specified key in an array through PHP code. For more related knowledge, please pay attention to the PHP Chinese website.

Related recommendations:

Reading a 1G file size through PHP

Explain the PHP class initialization function code

Explain PHP object-oriented, PHP inheritance related code

The above is the detailed content of How to use code to recursively obtain the value of a specified key in an array through PHP. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn