如果我有一个数组,例如:
testarray = array('foo'=>34, 'bar'=>array(1, 2, 3));
我将如何转换字符串testarray[bar][0]
以查找其描述的值?
如果我有一个数组,例如:
testarray = array('foo'=>34, 'bar'=>array(1, 2, 3));
我将如何转换字符串testarray[bar][0]
以查找其描述的值?
好吧,你可以做这样的事情(不是最漂亮的,但比安全得多eval
)......:
$string = "testarray[bar][0]";
$variableBlock = '[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*';
$regex = '/^('.$variableBlock.')((\[\w+\])*)$/';
if (preg_match($regex, $string, $match)) {
$variableName = $match[1]; // "testarray"
if (!isset($$variableName)) {
//Error, the variable does not exist
return null;
} else {
$array = $$variableName;
if (preg_match_all('/\[(\w+)\]/', $match[2], $matches)) {
foreach ($matches[1] as $match) {
if (!is_array($array)) {
$array = null;
break;
}
$array = isset($array[$match]) ? $array[$match] : null;
}
}
return $array;
}
} else {
//error, not in correct format
}