下面的代碼動態地將鍵連接到現有數組$options_pool
。所以最終的表格應該是:$options_pool[ $base_key ][ $first_key ][ $second_key ]
...這樣我就可以動態地爲數組$options_pool
這個多維的元素賦值。在PHP中動態形成變量名?
foreach($this->post_vars as $name => $value) {
//Look for $name key in array $options_pool if it exists.
//Use multi_array_key_exists() to handle the task
//It should return something like "fruit:mango:apple_mango"
//Then dynamically call $options_pool based on the data. Like so: $options_pool[ 'fruit' ][ 'mango' ][ 'apple_mango' ] = $value;
$match_key = multi_array_key_exists($name, $options_pool);
$option_keys = explode(':', $match_key);
$option_keys_length = count($option_keys);
$option_name_array = array();
if(0 < $option_keys_length) {
for($c = $option_keys_length; $c > 0; $c--) {
$sub_keys = '$options_pool';
for($c_sub = 0; $c_sub < $c ; $c_sub++) {
$sub_keys .= '[ $option_keys[ '. $c_sub . ' ] ]';
}
$option_name_array[] = $sub_keys;
}
foreach($option_name_array as $f_var_name) {
//the following line should equal to: $options_pool[ 'fruit' ][ 'mango' ][ 'apple_mango' ] = $value;
$f_var_name = $value;
}
}
}
//The $options_pool array
$options_pool = array('car' => '', 'animals' => '', 'fruit' => array('mango' => array('apple_mango' => ''));
我認爲邏輯是正確的除了這部分代碼:
foreach($option_name_array as $f_var_name) {
$f_var_name = $value; //particularly this line
}
不起作用?我測試了打印$f_var_name
的值,結果是正確的,但它並不真正調用數組?
PHP中的foreach結構在提供的數組副本上工作。 [瞭解更多。](http://php.net/manual/en/control-structures.foreach.php) – 2010-12-14 18:49:28
那麼可能的解決方法是什麼?我只是更新了我的問題,使其更清晰。 – Joann 2010-12-15 04:23:40