本文介绍了检索数组中给定子键的所有父键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在努力解决这个问题,但似乎找不到解决办法.我需要一个函数来检索给定子键的所有父键.因此,例如,如果我有一个像这样的数组:

I've been breaking my head over this one but can't seem to find a solution. I need a function that retrieves all parent keys of a given child key. So for example if I have an array like this:

array(
    'apples' => array(
        'bananas' => array(
            'strawberries' => array(
                'fruit' => array()
            )
        )
    )
)

我将调用像'key_get_parents($ key,$ array)'这样的函数,它将返回一个包含所有父键的数组.在此示例中为array('apples','bananas','strawberries').

I would call the function like 'key_get_parents($key, $array)', and it would return an array with all the parent keys. In this example that would be array('apples', 'bananas', 'strawberries').

推荐答案

$array = array(
    'apples' => array(
            'bananas' => array(
                    'strawberries' => array(
                            'fruit' => array()
                    )
            )
    )
 );

function key_get_parents($subject, $array)
{
  foreach ($array as $key => $value)
  {
    if (is_array($value))
    {
      if (in_array($subject, array_keys($value)))
        return array($key);
      else
      {
        $chain = key_get_parents($subject, $value);
        if (!is_null($chain))
          return array_merge(array($key), $chain);
      }
    }
  }

  return null;
}

// Prints "Array ( [0] => apples [1] => bananas )"
print_r(key_get_parents('strawberries', $array)); 

这篇关于检索数组中给定子键的所有父键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-24 06:01