0

我有数组数组:

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)
4

5 回答 5

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);
于 2013-02-27T09:10:50.423 回答
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]
于 2013-02-27T09:07:20.230 回答
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);
于 2013-02-27T09:28:54.370 回答
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);
于 2013-02-27T09:26:04.153 回答
-1

nameOfArray[3] = ["d", "e", "f"]。splice 也可以,但必须像这样使用:array.splice(index, howMany, whatToInsert)

于 2013-02-27T09:04:24.907 回答