2012-02-16 108 views
1

在下面的數組中,如何將新數組推送到指定位置的$ options數組中?將數組插入指定位置的指定位置

$options = array (
    array("name" => "My Options", 
    "type" => "title"), 
    array("type" => "open"), 

    array("name" => "Test", 
    "desc" => "Test", 
    "id" => $shortname."_theme", 
    "type" => "selectTemplate", 
    "options" => $mydir), 

//I want the pushed array inserted here. 

    array("name" => "Test2", 
    "desc" => "Test", 
    "id" => "test2", 
    "type" => "test", 
    "options" => $mydir), 

    array("type" => "close") 
    ); 

    if(someCondition=="met") 
    { 
    array_push($options, array("name" => "test", 
     "desc" => "description goes here", 
     "id" => "testMet", 
     "type" => "checkbox", 
     "std" => "true")); 
    } 

回答

7

您可以使用array_splice。對於你的例子:

if($some_condition == 'met') { 
    // splice new option into array at position 3 
    array_splice($options, 3, 0, array($new_option)); 
} 

注意array_splice預計最後一個參數是新元素的數組,所以你的例子中,你需要通過包含新的選項的數組的數組

2

只需

array_splice($options, 3, 0, $newArr); 
0

由於connec說,你可以使用array_splice,但沒有忘記來包裝你的陣列中的另一個數組,像這樣:

if ('met' === $some_condition) 
{ 
    array_splice($options, 3, 0, array(array(
    'name' => 'test', 
    'desc' => 'description goes here', 
    'id' => 'testMet', 
    'type' => 'checkbox', 
    'std' => 'true' 
))); 
} 

編輯: CONNEC已經指定其迴應。

1

用於插入新的陣列,而不是一個spesific位置(之間$ R [4]和$ R [5]):

$options[]=array ("key" => "val"); //insert new array 
$options[]=$v; //insert new variable 

插入spesific可變後一個新的數組:

function array_push(&$array,$after_element_number,$new_var) 
{ 
    array_splice($array, $after_element_number, 0, $new_var); 
} 

if(someCondition=="met") 
{ 
array_push($options, 2, array("name" => "test", 
    "desc" => "description goes here", 
    "id" => "testMet", 
    "type" => "checkbox", 
    "std" => "true")); 
}