2012-08-05 24 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