在PHP中动态形成变量名?

时间:2010-12-14 18:37:59

标签: php arrays

下面的代码动态地将键连接到现有数组$options_pool。所以最终的形式应该是:$options_pool[ $base_key ][ $first_key ][ $second_key ] ...这样我就可以动态地为数组$options_pool的元素赋值,这是多维的。

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的值并且结果是正确的但它并没有真正调用数组?

3 个答案:

答案 0 :(得分:1)

这是不对的,你是对的。 变量名始终$options_pool。 您可以将密钥作为explode(':', $name)传递,然后再分配它们。

顺便说一下,你的代码在

 foreach( $option_keys as $option_keys_value ) {
      $option_key_names[] = $option_keys_value;
 }

您是否意识到它只是将$option_keys复制为$option_key_names 只是,就好像您已编写$option_key_names = $option_keys;(在此代码中)?

也许有一个堆栈,你可以迭代地做这个,但是递归它更自然,正如你在这里看到的那样

function getVariableToWrite(&$reference, $nested_opts, $write) {
    if(empty($nested_ops)) // Base case
        return $reference = write;
    if(isset($reference[array_shift($nested_ops)]))
        return getVariableToWrite($reference, $nested_ops, $write);
    throw new Exception("The key does not exist..");
}

然后只是

foreach( $this->post_vars as $name => $value ) {
    // Your work over here until...
    $match_key = "fruit:mango:apple_mango";
    $option_keys = explode( ':', $match_key );

    getVariableToWrite($options_pool, $option_keys, $value);
}

这会起作用吗?

答案 1 :(得分:1)

foreach中,您需要通过引用传递值,以便进行编辑。

foreach( $option_name_array as &$f_var_name ){
  $f_var_name = $value;  
}

答案 2 :(得分:0)

试试这个......

foreach( $option_name_array as $key => $f_var_name ) {
    $option_name_array[$key] = $value; //particularly this line 
}