Accessing an arbitrarily deep key in a multi-dimen

2020-04-11 20:45发布

问题:

If I have an array that contains ['key1', 'key2', 'key3'] is there any way to map this to an array $array['key1']['key2']['key3'] without using loops or eval()?

Example of an array:

$var = [
    'key1' => [
        'subkey1' => [
            'finalkey' => 'value',
        ],
        'subkey' => [
            'otherkey' => 'value',
        ],
    ],
    'key2' => 'blah'
];

And then I have an array like this:

$keys = ['key1', 'subkey1', 'finalkey'] 

or

$keys = ['key1', 'subkey']

回答1:

function array_find($needle, &$haystack)
{
    $current = array_shift($needle);
    if(!isset($haystack[$current]))
    {
        return null;
    }
    if(!is_array($haystack[$current]))
    {
        return $haystack[$current];
    }
    return array_find($needle, $haystack[$current]);
}


回答2:

Untested, comes from a similar answer to a different question.

function get_value($dest, $path)
{
  # allow for string paths of a/b/c
  if (!is_array($path)) $path = explode('/', $path);

  $a = $dest;
  foreach ($path as $p)
  {
    if (!is_array($a)) return null;
    $a = $a[$p];
  }

  return $a;
}

This should perform better than recursive solutions.



回答3:

I came up with the following non-recursive method for my personal framework:

function Value($data, $key = null, $default = false)
{
    if (isset($key) === true)
    {
        if (is_array($key) !== true)
        {
            $key = explode('.', $key);
        }

        foreach ((array) $key as $value)
        {
            $data = (is_object($data) === true) ? get_object_vars($data) : $data;

            if ((is_array($data) !== true) || (array_key_exists($value, $data) !== true))
            {
                return $default;
            }

            $data = $data[$value];
        }
    }

    return $data;
}

Usage:

var_dump(Value($array, 'key1.subkey1.finalkey')); // or
var_dump(Value($array, array('key1', 'subkey1', 'finalkey')));

It could be further simplified by removing the object and default value support, as well as other checks.