php数组插入元素并保持键

时间:2012-08-05 10:19:08

标签: php arrays

这里我有我的数组(****只是字符串)

        [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] => ****

我知道插入数组的位置的关键值(在这种情况下:n_name

我做了什么:

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

但它没有正确放置$insertedarray,它会在我指定的位置添加此[0]=>null

我该如何解决这个问题?

2 个答案:

答案 0 :(得分:6)

您可以使用array_merge功能:

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

<强>更新

使用它来合并数组并保留键:

// 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));

答案 1 :(得分: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
)
*/
?>