将数组插入指定数组中的指定位置

时间:2012-02-16 22:39:02

标签: php arrays

在下面的数组中,如何将新数组推送到指定位置的$ 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"));
    }

4 个答案:

答案 0 :(得分: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期望最后一个参数是新元素的数组,因此对于您的示例,您需要传递一个包含新选项的数组阵列。

答案 1 :(得分:2)

简单

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

答案 2 :(得分:1)

用于插入新数组,而不是插入特定位置($ r [4]和$ r [5]之间):

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

在特定变量后插入一个新数组:

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"));
}

答案 3 :(得分: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已经指定了其响应。