用另一个数组将字符串转换为字符串

时间:2019-02-02 06:34:55

标签: php arrays sorting

我首先有两个数组:

$array1 = ['settings:rules:key','settings:scrum:way:other'];

我爆炸了$array1

$temp_array = explode(":",$array1);

现在我有另一个数组:

$array2 = [settings] => Array
        (  [rules] => Array
                (
                    [0] => Array
                        (
                            [key] => 
                            [showValueField] => 1
                     ) 
                )

类似这样的东西。

我需要使用第一个数组中给出的键访问第二个数组,例如:

$array2['settings']['rules']['key']

爆炸后我必须从第一个数组中获取此键

1 个答案:

答案 0 :(得分:1)

您可以通过这种循环来做到这一点:

function getVal($path, $arr) {
    $current = $arr[array_shift($path)];
    while (count($path)) {
        $key = array_shift($path);
        if (!is_array($current) || !isset($current[$key]))
            return false; // protect against non-existing keys
        $current = $current[$key];
    }
    return $current;
}

//example used:
$arr = array("settings" => array("rules" => array("key" => "AAA")));
echo getVal(explode(":",'settings:rules:key'), $arr) . PHP_EOL;