我有一个包含一些信息的数组,但我正在尝试实现一种使用可变变量动态访问数组的方法,但我不知道如何实现,因为 php 解释整个字符串是一个变量而不是具有关联键的变量。
我的示例代码:
$myArrayWithData = ["info" => 1];
$myvarvarArray = "myArrayWithData['info']";
print_r($$myvarvarArray);
预期行为:
1
实际行为:
`"Notice: Undefined variable: myArrayWithData['info']"`
我不想对索引进行硬编码,因为我正在尝试创建一个通过字符串创建数组索引路径的树枝函数,但我无法预测数组键。
$myvarvarArray = "myArrayWithData"
print_r($$myvarvarArray["info"]); #hardcoded index
编辑:我的函数可以添加超过 1 个索引
/**
* add a value to your twig array instead of using merge
*
* @param $object Array or object(public access) to set a new value
* @param string $context object complete path where value will be setted example "children.grandchildren.info"
* @param $value value to be inserted
*
*/
public function enhancedMerge($object, $contexts, $value){
$contexts = explode('.', $contexts);
$newObject = $object;
$path = '';
foreach($contexts as $key => $context){
$objectWithPath = 'newObject' . $path;
$contextIsArray = is_array(${$objectWithPath}) ? true : false;
if($contextIsArray){
$path .= "['" . $context . "']";
}else{
$path .= "->" . $context;
}
}
$objectWithPath = $newObject . $path;
$$objectWithPath = $value;
return $$newObject;
}