拼接数组

时间:2013-02-27 09:01:02

标签: php arrays splice

我有数组数组:

Array
(
   [0] => "title"
   [1] => Array
         (
             [0] => a
             [1] => b
             [2] => c
         )
   [2] => Array
         (
             [0] => d
             [1] => e
             [2] => f
         )
)

我需要在第一个数组中插入一个数组,如下所示

Array
(
   [0] => "title"
   [1] => Array
         (
             [0] => a
             [1] => b
             [2] => c
         )
   [2] => Array
         (
             [0] => a1
             [1] => b1
             [2] => c1
         )
   [3] => Array
         (
             [0] => d
             [1] => e
             [2] => f
         )
)

我不知道如何使用array_splice()。我试过这种方式,但它不起作用。

array_splice($main_array, 2, 0 $array_to_insert)

5 个答案:

答案 0 :(得分:2)

更新:阅读评论后,这似乎是一个javascript问题。 :) ?? !! ..只是为了完整性,这是一个PHP解决方案 - 按要求;)


array_splice()是正确的方法。使用以下代码:

<?php

$arr = array (
 'title',
 array('a', 'b', 'c'),
 array('d', 'e', 'f')
);
var_dump($arr);

// note that I've wrapped the array to be inserted into another, empty, array
array_splice($arr, 2, 0, array(array('a1', 'b1', 'c1')));

// further note that array_splice will not return the new array. $arr is
// passed by reference and will get modified from inside of array_splice
var_dump($arr);

答案 1 :(得分:1)

我认为这会对你有帮助......

    var a = [1,2,3,4,5];
a.splice(2,0,'a','b');  // Returns []; a is [1,2,'a','b',3,4,5]
a.splice(2,2,[1,2],3);  // Returns ['a','b']; a is [1,2,[1,2],3,3,4,5]

答案 2 :(得分:1)

$main_array = array(0 => "title",1 => array("a","b"));

$array_to_insert = array("c","d");

$new_array = array_splice($main_array, 1, 0, array($array_to_insert));

print_r($main_array);

答案 3 :(得分:0)

请检查以下代码

 $array_to_insert = array(0  => array( 0 => 'a1',1 => 'b1',2 => 'c1'));
   // You need to have nexted array

    $main_array = array(0 => "title",1 => array(0 => a,1 => b,2 => c),2 => array(0 => d,1 => 
e,2 => f));

    array_splice($main_array, 2, 0, $array_to_insert); 

    var_dump($main_array);

答案 4 :(得分:-1)

nameOfArray [3] = [“d”,“e”,“f”]。 splice也可以,但必须使用如下:array.splice(index,howMany,whatToInsert)