首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >PHP使用字符串作为数组键模式

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

Stack Overflow用户
提问于 2018-05-31 08:01:07
回答 1查看 45关注 0票数 0

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

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

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

EN

回答 1

Stack Overflow用户

发布于 2018-05-31 08:23:03

基于另一个问题: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!";
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50614883

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档