This question already has an answer here:
I have two array one is two dimensional
and second is one dimensional
and want to merge in a two dimensional array.
For Example :
# array1
Array
(
[0] => Array
(
[id] => 598
)
[1] => Array
(
[id] => 599
)
)
# array2
Array
(
[id] => 66
)
#resultant array
Array
(
[0] => Array
(
[id] => 598
)
[1] => Array
(
[id] => 599
)
[2] => Array
(
[id] => 66
)
)
In above example array1
and array2
are two input array and want to result as resultant array
.
I have tried array_merge
php function but it is not working.
How to do that?
</div>
If you just want to add an element it will work:
$array1[] = $array2;
If you want to create a new array it should work:
<?php
$array1 = [
0 => ['id' => 598],
1 => ['id' => 599],
];
$result_array = $array1;
$array2 = [
'id' => 66,
];
$result_array[] = $array2;
print_r($result_array);
?>
In this case just add to new element in $array1
an $array2
.
If you have more items in $array2
you can do it like follows:
$result_array = $array1;
foreach ($array2 as $key => $value) {
$result_array[] = [$key => $value];
}
print_r($result_array);
You can get the value from array_value then assign the id
key to your values and then merge your array.
$array1 = array(
array('id' => "2"),
array('id' => "3"),
);
$array2 = array(
'id' => "1"
);
$array2['id'] = array_values($array2);
$data = array_merge($array2,$array1);