我有一个在我的mysql抽象类中使用的函数(下面),并在“tableName.fieldName”字段中转换表名,并用指定变量(它对连接有用)替换它们。字段数组是很复杂的,所以我需要它来支持递归,以便它可以更改表名在array(array(array("tableName.fieldName")))
也为标准array("tableName.fieldName","tableName.field2Name",...)
PHP:递归保持变量的值?
然而,调试完毕后,我看到变量$i
和$fields_arr
保持相同的值,即使我传递$fields_arr
的新值,并且$i
在循环开始时设置。我怎样才能使这项工作,使$i
和$fields_arr
采取我传递给他们的新价值?
/**
* @param mixed $fields_arr standard array ("table.field1","table.field2",...)
* @param mixed $tables_and_vars eg. ("table1" => "tableVar1", "table2" => "tableVar2", ...)
* replaces all tablenames with desired tablevarnames
*/
private function tablesToTableVars($fields_arr, $tables_and_vars) {
// loop through every string
$numFields = count($fields_arr);
for($i = 0; $i < $numFields; $i++) {
$field = $fields_arr[$i];
if(is_numeric($field)) continue; // don't replace numbers
if(is_array($field)) {
$fields_arr[$i] = $this->tablesToTableVars($field, $tables_and_vars); // *** RECURSION ***
} else {
$tableNameLen = strpos($field, "."); // pos of period in string
if(strpos($field, ".") === false) continue; // don't replace fields that dont have tablenames
$searchTableName = substr($field, 0, $tableNameLen); // take 'table' from 'table.field'
// see if field contains a table
foreach($tables_and_vars as $tableName => $tableVar) {
if($searchTableName === $tableName) { // if it is the table name we're looking for
$fields_arr[$i] = $tableVar . substr($field, $tableNameLen); // change it to the variable name
break;
}
}
}
}
return $fields_arr;
}
你怎么知道$ numFields和$我保留价值?我看不到任何错误 – dbemerlin 2010-06-16 12:45:52
我得到了'Undefined offset:0',但我只是意识到我的数组是联想的,所以才有意义。谢谢! haha – gsquare567 2010-06-16 12:52:49
如果你已经知道了,请标记问题已经回答。谢谢, – David 2010-06-23 14:43:12