【问题标题】:Dynamic variable name for a multidimentional array多维数组的动态变量名
【发布时间】:2023-03-26 19:10:01
【问题描述】:

我的左手有这个“钥匙”: localisation.adresse.commune.id 和许多其他像这个一样的值,它们是动态的(我不能在我的代码中使用它们,因为我不知道它们会是什么)。

另一方面,我有一个这样的数组(来自一个 json 解码):

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

                        )

                )

        )

我无法列出我要利用的所有“密钥”,所以我需要自动获取 $object['localisation']['adresse']['commune']['id' 的值].

我试过了,但它不起作用:

$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']

我想它正在寻找一个复杂名称的简单变量,而不是查看多维数组,但我不知道我该怎么做......

感谢您的帮助!

【问题讨论】:

  • 你需要通过 json_decode 解码数组中的那个 json 字符串
  • 我已经做到了,使用 \GuzzleHttp\Utils::jsonDecode($objet, true);。这不是真正的问题,我可以从问题中删除 json 部分,我已经有一个关联数组:Array ( [localisation] => Array ( [adresse] => Array ( [adresse1] => Le Chatelard [codePostal] => 42820 [etat] => France [commune] => Array ( [id] => 16418 ) ) ) )

标签: php arrays recursion dynamic-programming


【解决方案1】:

除了遍历数组并尝试在内部数组中查找键(如果有的话)之外,我没有看到其他方法。

我想出了两种变体:递归和迭代。他们还将处理键和数组的“深度”不同的情况,例如如果您的 $key 包含的元素多于数组的深度,则将返回 NULL,如果少于 - 则返回最后一个键下的任何内容。

递归变体

$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)

迭代变体

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)

【讨论】:

  • 非常感谢您的帮助,我想我会选择递归的,它看起来正是我想要的:D thans !
【解决方案2】:

试试这个:

$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);

【讨论】:

  • 抱歉,我认为我的问题有误。我将 json 解码为数组没有任何问题:我的问题是我无法在 PHP 中编写 $data['localisation']['adresse']['commune']['id'],因为我不知道这些值:它们是动态的。它可以是 localisation.geoloc.gps.latitude,或 information.description,或 services.room... 或其他任何东西。在php中转换json真的不是这里的问题,sorry
  • 好的。我得到了你想要的东西,我的建议是不要创建动态变量,为什么不将 $keys 值拆分为“。”并使用它直接访问关联数组中的值。
  • 因为我不知道是否有 4 个或更多键。它可能是 information.services.key3.key4.key5... 所以将其转换为 ['information']['services']['key3']... 等然后尝试访问它会更舒服,而不是为此创建递归函数。在大量值上也可能是一个很大的性能问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-07-22
  • 2017-11-06
  • 2019-07-24
  • 2018-05-16
  • 2016-01-28
  • 2014-11-09
相关资源
最近更新 更多