PHP使用字符串作为数组键模式

时间:2018-05-31 00:01:07

标签: php

我需要一个字符串来将它用于数组模式以通过它来查找值。 例如

$test = ['test','test2' => ['test3','test4' => ['test5']]];
$pattern = "['test2']['test4']"
$response = $test{$pattern} <- search

给它一个解决这个问题的方法吗?

1 个答案:

答案 0 :(得分:1)

基于另一个问题:Using a string path to set nested array data

function GetValueFromPattern($arr, $pattern) {
    $exploded = explode(".",$pattern);

    $temp = $arr;
    foreach($exploded as $key) {
        if(key_exists($key, $temp)) {
            $temp = $temp[$key];
        } else {
            return ["status" => false];
        }
    }
    return ["status" => true, "response" => $temp];
}

$test = ['test','test2' => ['test3'=>"a",'test4' => ['test5']]];
$pattern = "test2.test3";
$response = GetValueFromPattern($test, $pattern);
if ($response["status"]) {
    echo $response["response"];
} else {
    echo "Error!";
}