PHP combine two associative arrays into one array
array_merge()
is more efficient but there are a couple of options:
$array1 = array("id1" => "value1");
$array2 = array("id2" => "value2", "id3" => "value3", "id4" => "value4");
$array3 = array_merge($array1, $array2/*, $arrayN, $arrayN*/);
$array4 = $array1 + $array2;
echo '<pre>';
var_dump($array3);
var_dump($array4);
echo '</pre>';
// Results:
array(4) {
["id1"]=>
string(6) "value1"
["id2"]=>
string(6) "value2"
["id3"]=>
string(6) "value3"
["id4"]=>
string(6) "value4"
}
array(4) {
["id1"]=>
string(6) "value1"
["id2"]=>
string(6) "value2"
["id3"]=>
string(6) "value3"
["id4"]=>
string(6) "value4"
}
PHP - Merge Two Associative Arrays where values match
Older & wiser: I've scrubbed my answer from years earlier because I no longer recommend the techniques. It will be most succinct and efficient to merge the arrays, feed them to a foreach()
loop, then "unite" (+
is used as an array union operator) data in related rows.
The null coalescing operator (??
) is used to ensure that there is always something to "unite" with.
Code: (Demo)
$result = [];
foreach (array_merge($array1, $array2) as $row) {
$result[$row['detail_image_id']] = ($result[$row['detail_image_id']] ?? []) + $row;
}
var_export(array_values($result));
Output:
array (
0 =>
array (
'detail_image_id' => '6389',
'product_name' => 'Starter broadband Package',
'guid' => 'http://xxx/wp-content/uploads/2018/04/broadband-4mbs-charji.jpg',
),
1 =>
array (
'detail_image_id' => '6358',
'product_name' => 'Starter broadband Package',
'guid' => 'http://xxx/wp-content/uploads/2018/04/broadband-4mbs-wingle.jpg',
),
)
How can I merge two associative arrays and preserve the global order of the entries?
Note that this solution will only work if the two arrays have the same length:
$arr1 = [ 'a' => '1', 'b' => 2 ];
$arr2 = [ 'h' => 'c', 'j' => '3' ];
$count = count($arr1);
$keys1 = array_keys($arr1);
$keys2 = array_keys($arr2);
$result = [];
for ($i = 0; $i < $count; $i++) {
$key1 = $keys1[$i];
$result[$key1] = $arr1[$key1];
$key2 = $keys2[$i];
$result[$key2] = $arr2[$key2];
}
print_r($result);
Output:
Array
(
[a] => 1
[h] => c
[b] => 2
[j] => 3
)
Edited based on mickmackusa's comment below.
Array merge on key of two associative arrays in php?
$output = array();
$arrayAB = array_merge($arrayA, $arrayB);
foreach ( $arrayAB as $value ) {
$id = $value['id'];
if ( !isset($output[$id]) ) {
$output[$id] = array();
}
$output[$id] = array_merge($output[$id], $value);
}
var_dump($output);
Optionally if you want to reset output's keys, just do:
$output = array_values($output);
Merge two associative arrays and group by first level key
You can use array_merge_recursive
to do the job.
array_merge_recursive
array_merge_recursive() merges the elements of one or more arrays together so that the values of one are appended to the end of the previous one. It returns the resulting array.
If the input arrays have the same string keys, then the values for these keys are merged together into an array, and this is done recursively, so that if one of the values is an array itself, the function will merge it with a corresponding entry in another array too. If, however, the arrays have the same numeric key, the later value will not overwrite the original value, but will be appended.
Just do:
<?php
$array1 = array(
"Test Stock" => array(
"intStockCount" => 10
),
"CARTON 50 X 50 X 50" => array(
"intStockCount" => 10
)
);
$array2 = array(
"Test Stock" => array(
"intInvoiceCount" => 20
),
"CARTON 50 X 50 X 50" => array(
"intInvoiceCount" => 30
)
);
$final = array_merge_recursive($array1,$array2);
echo '<pre>';
print_r($final);
echo '</pre>';
/* OUTPUT
Array
(
[Test Stock] => Array
(
[intStockCount] => 10
[intInvoiceCount] => 20
)
[CARTON 50 X 50 X 50] => Array
(
[intStockCount] => 10
[intInvoiceCount] => 30
)
)
*/
The important thing to notice here is that you are using the same string key
in both of your arrays
. As the PHP docs state
...the values for these keys are merged together into an array
how to merge two Associative Arrays in php
I'd do it like this:
<?php
// Object
$object = new stdClass();
$object->c_id = 743;
$object->userid = '570c842ce6073';
$object->comment = 'demo testing';
// Array containing object
$array1[0] = $object;
// Associative array
$array2 = array(
'hip' => 120,
'dummy1' => 100,
'dummy2' => 200
);
// Copying values from array2 to the object in array1 on key 0
foreach($array2 as $input => $key) {
$array1[0]->$key = $input;
}
// View array1 with new values from array2
print_r($array1);
?>
PHP - Merge two arrays (same-length) into one associative?
array_combine($keys, $values)
PS: Click on my answer! Its also a link!
Merge two associative arrays into one array for MongoDB Laravel 7
I was naive:
foreach (($newData) as $nd) {
$arrayPot = array_merge($oldData, array($nd));
}
Where $newData is:
$newData = array([
"repository_id" => $repositoryID,
"repository" => $request->repository,
"token" => $request->dataverse_token,
"url" => $request->dataverse_url,
]);
and $oldData holds the values for all the previous records for repository_data
My loop results in the following:
"repository_data" => array:4 [▼
0 => array:4 [▼
"repository_id" => 2
"repository" => "dataverse"
"token" => "123sdws"
"url" => "123"
]
1 => array:4 [▼
"repository_id" => 2
"repository" => "dataverse"
"token" => "kkkk"
"url" => "3333"
]
2 => array:4 [▼
"repository_id" => 2
"repository" => "dataverse"
"token" => "4444"
"url" => "5555555555"
]
3 => array:4 [▼
"repository_id" => 2
"repository" => "dataverse"
"token" => "1111"
"url" => "22333"
]
]
I still don't understand that $newData must be an array and then again declare it as an array inside my foreach loop
PHP efficient way to combine two associative arrays into one multidimensional associative array
Build an index :
you need to access your salesPerson
entries by id, you can start by creating an associative array id => salesPerson
, and then use this associative array in your loop.
$salesById = array();
foreach ($salesPersons as $s_record) {
$salesById[ $s_record['id'] ] = $s_record;
}
$result = array();
foreach ($clients as $c_record) {
$s_record = $salesById[ $c_record['salesPersonId'] ];
if ($s_record == null) {
// you may want to handle invalid ids in the client array
// one way is to simply ignore this client record :
continue;
}
array_push($s_record['clients'], array(
"id" => $c_record['id'],
"name" => $c_record['name']
));
array_push($result, $s_record);
}
Notes
There may be a problem in the way you create your $result
array :
if a sales person has n
clients, the $result
array will reference that sales person n
times.
Look closer into what result you actually want, you may simply want to return $salesPersons
, or $salesById
.
Related Topics
Warning: MySQLi_Error() Expects Exactly 1 Parameter, 0 Given Error
Truncate Float Numbers with PHP
Error While Using Pdo Prepared Statements and Limit in Query
How to Pass Variables Received in Get String Through a PHP Header Redirect
Read Large Data from CSV File in PHP
Magento Upgrade Takes Too Long and Never Completes
Why Should I Fix E_Notice Errors
Extending the Controller Class in Codeigniter
File_Get_Contents - Failed to Open Stream: Http Request Failed! Http/1.1 404 Not Found
Apache Rewrite - Get Original Url in PHP
How to Display Image from Database Using PHP
Check for Consecutive Dates Within a Set and Return as Range
How to Call a Model from a View
How to Extract Query Parameters from a Url String in PHP
Mysqli Error: User Already Has More Than 'Max_User_Connections' Active Connections