当前位置: 动力学知识库 > 问答 > 编程问答 >

php - Dynamically adding an associative multidimentional array to an array containing another associative multidimentional array?

问题描述:

I am trying to dynamically generate an multidimensional array where the $value of the $key=>$value pairs is another multidimensional array. The keys are going to generate dynamically through a select menu (which itself is dynamically generated, so I wont know the names of keys).

It's for a WordPress plugin so there are some WP functions in the following code:

$var1 = $_POST['var1'];

$var2 = $_POST['var2'];

if (get_option('option_name') != null) {

$option = get_option('option_name');

$option[$var2] = array('sync'=>1,'setting1'=>$var2,'setting2'=>$var1);

update_option('option_name', $option[$var2]);

} else {

$option = array();

$option[$var2] = array('sync'=>1,'setting1'=>$var2,'setting2'=>$var1);

update_option('option_name', $option[$var2]);

}

Basically, the "else" part of this, indicating that get_option('option_name') is empty or not set, is working great and after the update_option function is called I get:

Array

(

[firstvar2] => Array

(

[sync] => 1

[setting1] => firstvar2

[setting2] => firstvar1

)

)

Which is exactly what I want. The problem I am having is adding an additional associative array when this first one is already present. The 'if' part of the conditional is giving me this:

Array

(

[sync] => 1

[setting1] => firstvar2 //(from the first run)

[setting2] => firstvar1 //(from the first run)

[secondvar2] => Array //(from the second run)

(

[sync] => 1

[setting1] => secondvar2 //(from the second run)

[setting2] => secondvar1 //(from the second run)

)

)

How can I get this instead?:

Array

(

[firstvar2] => Array //first run

(

[sync] => 1 //first run

[setting1] => firstvar2 //first run

[setting2] => firstvar1 //first run

)

[secondvar2] => Array //second run

(

[sync] => 1 //second run

[setting1] => secondvar2 //second run

[setting2] => secondvar1 //second run

)

)

网友答案:

you should update all of the $option update_option( 'option_name', $option ); what is happening is basically your always setting $option equal to $option[ $var2 ]

分享给朋友:
您可能感兴趣的文章:
随机阅读: