我有一个数组与一些信息,但我试图实现一种方式来访问数组动态变量变量,但我不知道如何,因为PHP解释整个字符串是一个变量,而不是一个变量与关联键。
我的示例代码:$myArrayWithData = ["info" => 1];
$myvarvarArray = "myArrayWithData['info']";
print_r($$myvarvarArray);
预期行为:
1
实际行为:`"Notice: Undefined variable: myArrayWithData['info']"`
我不想硬编码索引,因为我试图创建一个分支函数,创建一个字符串的数组索引路径,我不能预测数组键。
$myvarvarArray = "myArrayWithData"
print_r($$myvarvarArray["info"]); #hardcoded index
编辑:我的函数可以添加一个以上的索引
/**
* 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;
}
我可以用变量访问数组键吗?
简短回答:No.
但是,我们可以像这样使用引用变量访问它们。
我的函数现在向数组twigs添加值
public function enhancedMerge($object, $contexts, $value)
{
$contexts = explode('.', $contexts);
$elemCount = count($contexts);
$current = &$object;
foreach ($contexts as $key => $context) {
if (is_array($current)) {
$current = &$current[$context];
} elseif ($key != $elemCount-1) {
$current = &$current->$context;
}
}
$backup = $current;
$current = $value; #set new value and modify $object by reference
return $object;
}