PHP: recursion keeps values for variables?
i have a function (below) which is used in my mysql abstraction开发者_开发技巧 class and converts table names in fields like "tableName.fieldName" and replaces them with the specified variables (it's useful for joins). the array of fields is very mixed, and so i need it to support recursion so that it can change the table names in an array(array(array("tableName.fieldName")))
but also for the standard array("tableName.fieldName","tableName.field2Name",...)
however, after debugging, i see that the variables $i
and $fields_arr
are maintaining the same values, even though i pass on a new value for $fields_arr
and $i
is set at the begining of the loop. how can i make this work so that $i
and $fields_arr
take the new values i pass for them?
/**
* @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;
}
can't use integer indexes for an associative array =)
精彩评论