Reputation: 8962
here i've got my array(the ****
are just strings)
[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] => ****
how can i insert another array:
[n_group] => ****
[n_available] => ****
into the original one so that it looks like:
[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] => ****
i know the key value of where to insert the array(in this case: n_name
)
What i did:
$pos = intval(array_search("n_name", $myarray))+1;
array_splice($myarray, $pos, 0, $insertedarray);
but it doesn't put the $insertedarray
properly, it adds this [0]=>null
in the position I specified
how can i solve this?
Upvotes: 1
Views: 3704
Reputation: 1034
you could use array_push http://php.net/manual/en/function.array-push.php
source: php manual(examples)
<?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
)
*/
?>
Upvotes: 0
Reputation: 27594
You can use array_merge
function:
$out = array_merge($first_array, $second_array);
UPDATE
Use this to merge your arrays and preserve keys:
// 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));
Upvotes: 6