2012-08-05 25 views
1

在这里,我有我的阵列(在****仅仅是字符串)PHP数组元素插入并保持键

 [m_timestamp] => **** 
     [n_id] => **** 
     [n_name] => **** 
     [n_material] => **** 
     [n_neck_finish] => **** 
     [n_weight] => **** 
     [n_height] => **** 
     [n_qty_p_ctn] => **** 
     [n_ctn_dimensions] => **** 
     [n_comment] => **** 
     [sha1] => **** 

我怎么可以插入另一个数组:

 [n_group] => **** 
     [n_available] => **** 

成原来的一个,这样它看起来像:

 [m_timestamp] => **** 
     [n_id] => **** 
     [n_name] => **** 
     [n_group] => **** //inserted 
     [n_available] => **** //inserted 
     [n_material] => **** 
     [n_neck_finish] => **** 
     [n_weight] => **** 
     [n_height] => **** 
     [n_qty_p_ctn] => **** 
     [n_ctn_dimensions] => **** 
     [n_comment] => **** 
     [sha1] => **** 

我知道在哪里插入T中的键值他数组(在这种情况下:n_name

我做了什么:

$pos = intval(array_search("n_name", $myarray))+1; 
array_splice($myarray, $pos, 0, $insertedarray); 

,但它并没有把$insertedarray得当,它会将此[0]=>null在我指定的

怎能位置我解决这个问题?

+0

可能重复的[如何插入元件成阵列,以特定的位置?](http://stackoverflow.com/questions/3353745/how-to-insert-element-排列到特定位置) – 2012-08-05 10:22:57

回答

6

可以使用array_merge功能:

$out = array_merge($first_array, $second_array); 

UPDATE

使用此合并您的阵列和维护密钥:

// slice $myarray into two parts and insert $insertedarray in between 
// keys are preserved 
$myarray = array_merge(array_slice($myarray, 0, $pos), $insertedarray, array_slice($myarray, $pos)); 
+0

+1你打我:D – Havelock 2012-08-05 10:22:01

+0

但我需要指定插入位置(位置)..... – tom91136 2012-08-05 10:22:24

+0

@ Tom91136这是为什么?你正在使用关联数组 – Zbigniew 2012-08-05 10:22:50

0

你可以使用array_push http://php.net/manual/en/function.array-push.php

源:PHP手册(示例)

<?php 

function array_put_to_position(&$array, $object, $position, $name = null) 
{ 
     $count = 0; 
     $return = array(); 
     foreach ($array as $k => $v) 
     { 
       // insert new object 
       if ($count == $position) 
       { 
         if (!$name) $name = $count; 
         $return[$name] = $object; 
         $inserted = true; 
       } 
       // insert old object 
       $return[$k] = $v; 
       $count++; 
     } 
     if (!$name) $name = $count; 
     if (!$inserted) $return[$name]; 
     $array = $return; 
     return $array; 
} 
?> 

Example : 

<?php 
$a = array(
'a' => 'A', 
'b' => 'B', 
'c' => 'C', 
); 

print_r($a); 
array_put_to_position($a, 'G', 2, 'g'); 
print_r($a); 

/* 
Array 
(
    [a] => A 
    [b] => B 
    [c] => C 
) 
Array 
(
    [a] => A 
    [b] => B 
    [g] => G 
    [c] => C 
) 
*/ 
?> 
+0

我知道,但我如何指定位置? – tom91136 2012-08-05 10:25:56

+0

看看你的评论早些时候可能你需要的是解决方法 – lgt 2012-08-05 10:27:37