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

问题描述

我试图找到一种方法来返回数组的父键的值.

I'm trying to find a way to return the value of an array's parent key.

例如,从下面的数组中,我想找出 $array['id'] == "0002" 的父键.父键很明显,因为它在此处定义(它将是产品"),但通常它是动态的,因此存在问题.'id' 和 'id' 的值是已知的.

For example, from the array below I'd like to find out the parent's key where $array['id'] == "0002".The parent key is obvious because it's defined here (it would be 'products'), but normally it'd be dynamic, hence the problem. The 'id' and value of 'id' is known though.

    [0] => Array
        (
            [data] =>
            [id] => 0000
            [name] => Swirl
            [categories] => Array
                (
                    [0] => Array
                        (
                            [id] => 0001
                            [name] => Whirl
                            [products] => Array
                               (
                                    [0] => Array
                                        (
                                            [id] => 0002
                                            [filename] => 1.jpg
                                         )
                                    [1] => Array
                                        (
                                            [id] => 0003
                                            [filename] => 2.jpg
                                         )
                                )
                         )
                 )
          )

推荐答案

有点粗糙的递归,但它应该可以工作:

A little crude recursion, but it should work:

function find_parent($array, $needle, $parent = null) {
    foreach ($array as $key => $value) {
        if (is_array($value)) {
            $pass = $parent;
            if (is_string($key)) {
                $pass = $key;
            }
            $found = find_parent($value, $needle, $pass);
            if ($found !== false) {
                return $found;
            }
        } else if ($key === 'id' && $value === $needle) {
            return $parent;
        }
    }

    return false;
}

$parentkey = find_parent($array, '0002');

这篇关于PHP - 查找数组的父键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 07:10