1

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

        [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到我指定的位置

我该如何解决这个问题?

4

2 回答 2

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));
于 2012-08-05T10:21:26.897 回答
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
)
*/
?>
于 2012-08-05T10:22:35.747 回答