How can I merge multiple arrays into one that have same column. My codes are like
$stmt1 = $pdo ->prepare('SELECT * FROM `formsone`');
$stmt1 ->execute();
$applications1 = $stmt1 ->fetchAll();
$stmt2 = $pdo ->prepare('SELECT * FROM `formstwo`');
$stmt2 ->execute();
$applications2 = $stmt2 ->fetchAll();
$stmt3 = $pdo ->prepare('SELECT * FROM `formsthree`');
$stmt3 ->execute();
$applications3 = $stmt3 ->fetchAll();
$stmt4 = $pdo ->prepare('SELECT * FROM `formsfour`');
$stmt4 ->execute();
$applications4 = $stmt4 ->fetchAll();
$results = // Merge all applications into one
They all have same columns like id
, name
, password
, I just want to combine all of the results into one.
Ok let's assume that you have 4 arrays:
<?php
$data1=[
'id' => 1,
'name' => 'test1',
'password' => 'pass1'
];
$data2=[
'id' => 2,
'name' => 'test2',
'password' => 'pass2'
];
$data3=[
'id' => 3,
'name' => 'test3',
'password' => 'pass3'
];
$data4=[
'id' => 4,
'name' => 'test4',
'password' => 'pass4'
];
They all have the same fields as you mentioned. In order to merge them you can use:
$result=array_merge_recursive($data1,$data2,$data3,$data4);
echo '<pre>';
print_r($result);
The output will be a new array including all the merged data based on the key values of each array:
Array
(
[id] => Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
)
[name] => Array
(
[0] => test1
[1] => test2
[2] => test3
[3] => test4
)
[password] => Array
(
[0] => pass1
[1] => pass2
[2] => pass3
[3] => pass4
)
)
In this example array_merge
will not work properly because while creating the new array it will override the data because of the same array_key
(id,name,password in our example). That's why i used array_merge_recursive
which created a multi-dimensional array based on the key values.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.