动态添加元素到多维关联数组

时间:2012-08-31 16:48:07

标签: php arrays dynamic add associative

我正在尝试将新元素插入多维关联数组,如

$arr=array('ID' => 123,
           'name' => 'rock',
           'accountID' => 'u0777f7f-77f7-4d2e-9h7c-ea775d052785',
           'admin' => array  (
                       'main' => array (
                                   'stats' =>'', 
                                   'emails' =>'', 
                                   'calls' => ''
                                )
                         )
            );

 $list='';
 $list .="['admin']['main']['hello']";

 $arr{$list}='world';
 print_r($arr);

但是新元素没有被添加到['admin'] ['main'],而是它正在创建新的数组元素,如

Array
(
    [ID] => 123
    [name] => rock
    [accountID] => u0777f7f-77f7-4d2e-9h7c-ea775d052785
    [admin] => Array
        (
            [main] => Array
                (
                    [stats] => 
                    [emails] => 
                    [calls] => 
                )

        )
   [['admin']['main']['hello']] => world
)

请帮我解决一下。 感谢

2 个答案:

答案 0 :(得分:2)

[['admin']['main']['hello']] => world

这是因为 STRING

考虑了$ list

尝试更改此行

$list='';
$list .="['admin']['main']['hello']"; 
$arr{$list}='world';
print_r($arr);

$list = array();
$list['main']['hello'] = "world";
$arr['admin'] = $list;
print_r($arr);

魔法将被揭示。洛尔


如果你想要$ arr喜欢:

Array ( 
     [ID] => 123 
     [name] => rock 
     [accountID] => u0777f7f-77f7-4d2e-9h7c-ea775d052785 
     [admin] => Array ( 
                    [main] => Array ( 
                         [stats] => 
                         [emails] => 
                         [calls] => 
                                    ) 
                       ) 
     [hello] => world 
      )

您可以逻辑地书写

$arr = array();

$arr['ID'] = 123;
$arr['name'] = "rock";
$arr['accountID'] = "u0777f7f-77f7-4d2e-9h7c-ea775d052785";

$arr['admin']['main']['stats'] = "complete";
$arr['admin']['main']['emails'] = "example@email.com";
$arr['admin']['main']['calls'] = "yourfunction";
$arr['hello'] = "world";

答案 1 :(得分:0)

这是你应该做的:

$arr['admin']['main']['hello'] = > 'world';

OR

$main = $arr['admin']['main'];
$main['hello'] = 'world';