从php函数向符号表中添加变量
我目前正在使用大量使用关联数组的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
)
)
是否有可能创造条件,能够将这些变量添加到符号表还是我只是坚持能够回报他们的功能?
这是如何工作的吗?
foreach($input_array as $key => $value){
$variable_name = strtolower($key);
$$variable_name = array($value);
}
希望帮助...
$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
该变量的范围是什么?它可以在每个地方或者在它被调用的函数内访问吗? –
请阅读以下内容http://php.net/manual/en/language.variables.scope.php – Cyclonecode
您还应该检出提取功能http://php.net/manual/en/function.extract.php – Cyclonecode
你想要的东西,比如'$ =后数组($用户[ '邮政']);'? – deceze
似乎有点多余;为什么? – Ross