度日值的所有数组键 [英] get all array keys by value

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

问题描述

让我们说,我有一个这样的数组:

 阵列

[开始] = GT;排列
    (
        [项目1] =>排列
            (
                [0] =>项目1_1
                [项目2_1] =>排列
                    (
                        [项目2_1_1] => X
                    )                [1] =>项目3_1
            )        [0] =>项目2
        [1] =>项目3
    )

有没有办法,我可以用它来获得通向值路径的PHP函数 X 在我的数组,这意味着,在这种情况下,结果将是:

 开始,项目1,项目2_1,项目2_1_1,X


解决方案

目前,我能想到的将是大量的嵌套的的foreach($数组$关键=> $值)的唯一方法 array_search一起循环()

这将是更好的设计,使之递归人会想到,所以使用功能将是明智的。

 函数recursiveSearch($键,$阵列)
{
    的foreach($数组作为$ K => $ AR){
        如果(is_array('x'的,$ AR)){
            返回$ķ。 ','。 array_search('X',$ AR);
        }其他{
            如果($ AR ==='X'){
                返回$ķ
            }其他{
                返回recursiveSearch($键,$ AR);
            }
        }
    }
}

刚上它取,不一定是工作或类似的东西。

Let's say that I have an array like this:

Array
(
[Start] => Array
    (
        [Item 1] => Array
            (
                [0] => Item 1_1
                [Item 2_1] => Array
                    (
                        [Item 2_1_1] => x
                    )

                [1] => Item 3_1
            )

        [0] => Item 2
        [1] => Item 3
    )

)

Is there a php function that I can use to get the path that leads to the value x in my array, meaning, in this case the result would be:

Start, Item 1, Item 2_1, Item 2_1_1, x

解决方案

The only method I can currently think of would be plenty of nested foreach ($array as $key => $value) loops together with array_search().

It would be better design to make it a recursive one though, so using a function would be wise.

function recursiveSearch($key, $array)
{
    foreach ($array as $k => $ar) {
        if (is_array('x', $ar)) {
            return $k . ', ' . array_search('x', $ar);
        } else {
            if ($ar === 'x') {
                return $k
            } else {
                return recursiveSearch($key, $ar);
            }
        }
    }
}

Just a take on it, not necessarily working or something like that.

这篇关于度日值的所有数组键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆