2011-11-20 34 views
0

我目前正在使用大量使用关联数组的CakePHP。对于我的应用程序中的其中一个函数,如果我可以从这些数组中的某些数据创建单独的变量,将会非常有用。例如数组可能看起来像这样:从php函数向符号表中添加变量

Array 
(
    [User] => Array 
     (
      [id] => 1 
      [name] => Joe Bloggs 
      [email] => [email protected] 
     ) 

    [Post] => Array 
     (
      [id] => 1 
      [title] => Hello World 
     ) 

    [Profile] => Array 
     (
      [id] => 1 
      [location] => London 
     ) 

) 

我想创造一种可以在3阵列分裂,并给我三个新变量的函数。

我看过extract(),但它并没有按照我想要的方式工作。我想创建三个新的变量,例如:

$user: 

Array 
(
    [User] => Array 
     (
      [id] => 1 
      [name] => Joe Bloggs 
      [email] => [email protected] 
     ) 
) 

$post: 

Array(
    [Post] => Array 
     (
      [id] => 1 
      [title] => Hello World 
     ) 
) 

$profile: 

Array(
    [Profile] => Array 
     (
      [id] => 1 
      [location] => London 
     ) 
) 

是否有可能创造条件,能够将这些变量添加到符号表还是我只是坚持能够回报他们的功能?

+0

你想要的东西,比如'$ =后数组($用户[ '邮政']);'? – deceze

+0

似乎有点多余;为什么? – Ross

回答

1

这是如何工作的吗?

foreach($input_array as $key => $value){ 

    $variable_name = strtolower($key); 
    $$variable_name = array($value); 

} 

希望帮助...

+0

我假设我正在寻找的是$$?这是否使该变量可用于调用功能?我在哪里可以在php手册中找到关于这方面的信息,不确定要搜索什么,因为搜索'$$'并没有太大的帮助。 –

+0

它使用$ variable_name的值作为变量名称,它必须是字符串 – Homer6

+0

@Mike http://php.net/manual/en/language.variables.variable.php – deceze

2
$array = array(
'value1'=> array('name' => 'john'), 
'value2'=> array('name' => 'sim') 
); 
function createVars($data) { 
    foreach ($data as $key => $val) { 
    global ${$key}; 
    ${$key} = $val; 
    } 
} 
createVars($array); 
// Now you should be able to access $value1 and $value2 

退房此链接http://php.net/manual/en/language.variables.variable.php

+0

该变量的范围是什么?它可以在每个地方或者在它被调用的函数内访问吗? –

+0

请阅读以下内容http://php.net/manual/en/language.variables.scope.php – Cyclonecode

+0

您还应该检出提取功能http://php.net/manual/en/function.extract.php – Cyclonecode