I want to merge two different array data in one array, but i'm confuse how to use array_push
in this case.
this is example of my data input:
["author"]=>
array(2) {
[0]=>
string(1) "John"
[1]=>
string(1) "Doe"
}
["title"]=>
array(2) {
[0]=>
string(1) "book a"
[1]=>
string(1) "book b"
}
And the result in one array that i mean, like this:
["books"]=>
array(2) {
[0] =>
array(2) {
["author"]=>
string(1) "John"
["title"]=>
string(1) "book a"
}
[1] =>
array(2) {
["author"]=>
string(1) "Doe"
["title"]=>
string(1) "book b"
}
}
I already try using this way but it just return 1 from each array:
$data['books'] = [];
array_push($data['books'], [
'author' => $data['author'],
'title' => $data['title']
]);
if (isset($data['books'])) {
foreach ($data['books'] as $k => $v) {
$data['books'][$k]['author'] = (int)$v['author'];
$data['books'][$k]['title'] = (int)$v['title'];
}
}
result:
["books"]=>
array(1) {
[0]=>
array(2) {
["author"]=>
int(1)
["title"]=>
int(1)
}
}
My Answer:
$array1 = [1, 2, 3];
$array2 = ['a', 'b', 'c'];
$mergedArray = [];
foreach($array1 as $value) {
array_push($mergedArray, $value);
}
foreach($array2 as $value) {
array_push($mergedArray, $value);
}
print_r($mergedArray);
?>
This code will merge the two arrays $array1 and $array2 into a single array $mergedArray using array_push.
Rate this post
3 of 5 based on 7753 votesComments