2011-11-20 51 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