如果我有一个数组如:
testarray = array('foo'=>34, 'bar'=>array(1, 2, 3));
如何转换testarray[bar][0]
之类的字符串以查找其描述的值?
答案 0 :(得分:2)
嗯,你可以做这样的事情(不是最漂亮,但比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
}
答案 1 :(得分:1)