首页 > 解决方案 > PHP 使用字符串作为数组键模式

问题描述

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

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

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

标签: php

解决方案


基于另一个问题: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!";
}

推荐阅读