php - PHP 使用字符串作为数组键模式
问题描述
我需要一个字符串来将它用于数组模式以通过它来查找值。例如
$test = ['test','test2' => ['test3','test4' => ['test5']]];
$pattern = "['test2']['test4']"
$response = $test{$pattern} <- search
给它一个解决这个问题的方法?
解决方案
基于另一个问题: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!";
}
推荐阅读
- java - EditText 数字分组仅显示 4 个字符
- javascript - 我如何将 2 个提示答案转换为 1 个结果以进行连接
- ios - 您是否需要提供每个图标尺寸才能将您的应用发布到应用商店?iOS
- python - 如何在python中创建一个链表
- python - 使用 write() 方法合并两个文本文件时删除了行
- c# - A way to add int value to textbox with a button click and then subtract from the int value with another button
- python - 从蒙特卡洛总结场景
- java - 从不同的类访问时方法不执行
- swift - 通过 Segue 将对象从表视图单元传递到另一个视图控制器
- node.js - 无法从 Gitlab CI/CD 在 AWS RDS 数据库中运行迁移