简体   繁体   English

多维数组的动态变量名

[英]Dynamic variable name for a multidimentional array

On my left hand I've got this "key" : localisation.adresse.commune.id and many other values like this one, wich are dynamics (i can't use them literraly in my code as i don't know what they will be).在我的左手上,我有这个“钥匙”: localisation.adresse.commune.id和许多其他类似的值,这是动态的(我不能在我的代码中逐字地使用它们,因为我不知道它们是什么)将会)。

On the other hand i have an array like this (comes fron a json decoded) :另一方面,我有一个这样的数组(来自 json 解码):

    Array
        (
            [localisation] => Array
                (
                    [adresse] => Array
                        (
                            [adresse1] => Le Chatelard
                            [codePostal] => 42820
                            [etat] => France
                            [commune] => Array
                                (
                                    [id] => 16418
                                )

                        )

                )

        )

I can't list all the "keys" i'm going to exploit, so I need to automatically get the value of $object['localisation']['adresse']['commune']['id'].我无法列出我将要利用的所有“密钥”,因此我需要自动获取 $object['localisation']['adresse']['commune']['id'] 的值。

I've tried this but it does not work :我试过这个,但它不起作用:

$test['localisation']['adresse']['commune']['id'] = 16418 ;
$var = '$test[\'localisation\'][\'adresse\'][\'commune\'][\'id\']' ;
echo $var ; // $test['localisation']['adresse']['commune']['id']
var_dump($$var) ; // NULL Notice: Undefined variable: $test['localisation']['adresse']['commune']['id']
var_dump(${$var}) ; // NULL Notice: Undefined variable: $test['localisation']['adresse']['commune']['id']

I suppose it's looking for a simple variable of a complicated name, instead of looking at a multidimentional array, but i don't know how i can do it...我想它正在寻找一个复杂名称的简单变量,而不是查看多维数组,但我不知道我该怎么做......

Thans for your help !感谢您的帮助!

I see no other way except traversing the array and trying to find the keys in internal arrays, if there are any.除了遍历数组并尝试在内部数组中查找键(如果有)之外,我看不到其他方法。

I came up with two variants: recursive and iterative.我想出了两种变体:递归和迭代。 They will also handle the case when the "depth" of the key and array differ, eg if your $key will contain more elements than the depth of the array, then the NULL will be returned, if less - then whatever is under the last key will be returned.当键和数组的“深度”不同时,它们还将处理这种情况,例如,如果您的$key包含的元素多于数组的深度,则将返回NULL ,如果更少 - 那么最后一个钥匙将被退回。

Recursive variant递归变体

$a = [
    'localisation' => [
        'adresse' => [
            'adresse1' => 'Le Chatelard',
            'codePostal' => 42820,
            'etat' => 'France',
            'commune' => [
                'id' => 16418,
            ],
        ],
    ],
];

$key = 'localisation.adresse.commune.id';

function getValueByKeyRecursively($a, $key)
{
    $keyList = explode('.', $key);
    $currentKey = array_shift($keyList);

    // Found the value
    if (empty($currentKey)) {
        return $a;
    }

    // No more depth to traverse or no such key
    if (!is_array($a) || !array_key_exists($currentKey, $a)) {
        return null;
    }

    return getValueByKeyRecursively($a[$currentKey], implode('.', $keyList));
}

var_dump(getValueByKeyRecursively($a, $key)); // outputs: int(16418)

Iterative variant迭代变体

function getValueByKey(array $a, $key)
{
    $keyList = explode('.', $key);
    $returnValue = $a;

    do {
        $currentKey = array_shift($keyList);

        // Found the value
        if ($currentKey === null) {
            break;
        }

        // No more depth to traverse or no such key
        if (!is_array($returnValue) || !array_key_exists($currentKey, $returnValue)) {
            return null;
        }

        $returnValue = $returnValue[$currentKey];

    } while (true);

    return $returnValue;
}

var_dump(getValueByKey($a, $key)); // outputs: int(16418)

try this :尝试这个 :

$str = '{
        "localisation" : {
            "adresse" : {
                "adresse1" : "Le Chatelard",
                "codePostal" : "42820",
                "etat" : "France",
                "commune" : {
                    "id" : 16418
                }
            }
        }
    }
        ';

$data = json_decode($str, true);
$var = $data['localisation']['adresse']['commune']['id'] ;
echo $var ;
print_r($data);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM