PHP combine two associative arrays into one array
up vote
55
down vote
favorite
$array1 = array("$name1" => "$id1");
$array2 = array("$name2" => "$id2", "$name3" => "$id3");
I need a new array combining all together, i.e. it would be
$array3 = array("$name1" => "$id1", "$name2" => "$id2", "$name3" => "$id3");
What is the best way to do this?
Sorry, I forgot, the ids will never match each other, but technically the names could, yet would not be likely, and they all need to be listed in one array. I looked at array_merge but wasn't sure if that was best way to do this. Also, how would you unit test this?
php arrays multidimensional-array associative-array
add a comment |
up vote
55
down vote
favorite
$array1 = array("$name1" => "$id1");
$array2 = array("$name2" => "$id2", "$name3" => "$id3");
I need a new array combining all together, i.e. it would be
$array3 = array("$name1" => "$id1", "$name2" => "$id2", "$name3" => "$id3");
What is the best way to do this?
Sorry, I forgot, the ids will never match each other, but technically the names could, yet would not be likely, and they all need to be listed in one array. I looked at array_merge but wasn't sure if that was best way to do this. Also, how would you unit test this?
php arrays multidimensional-array associative-array
5
Sounds like you're probably just looking for array_merge.
– Corbin
Nov 1 '12 at 2:47
I think the best way, if you know the keys are all different, is to use the += operator: $array1 += $array2; This appends all the elements of $array2 to the end of $array1.
– David Spector
Nov 10 at 19:49
add a comment |
up vote
55
down vote
favorite
up vote
55
down vote
favorite
$array1 = array("$name1" => "$id1");
$array2 = array("$name2" => "$id2", "$name3" => "$id3");
I need a new array combining all together, i.e. it would be
$array3 = array("$name1" => "$id1", "$name2" => "$id2", "$name3" => "$id3");
What is the best way to do this?
Sorry, I forgot, the ids will never match each other, but technically the names could, yet would not be likely, and they all need to be listed in one array. I looked at array_merge but wasn't sure if that was best way to do this. Also, how would you unit test this?
php arrays multidimensional-array associative-array
$array1 = array("$name1" => "$id1");
$array2 = array("$name2" => "$id2", "$name3" => "$id3");
I need a new array combining all together, i.e. it would be
$array3 = array("$name1" => "$id1", "$name2" => "$id2", "$name3" => "$id3");
What is the best way to do this?
Sorry, I forgot, the ids will never match each other, but technically the names could, yet would not be likely, and they all need to be listed in one array. I looked at array_merge but wasn't sure if that was best way to do this. Also, how would you unit test this?
php arrays multidimensional-array associative-array
php arrays multidimensional-array associative-array
edited Nov 1 '12 at 2:59
asked Nov 1 '12 at 2:45
jsteinmann
2,09121119
2,09121119
5
Sounds like you're probably just looking for array_merge.
– Corbin
Nov 1 '12 at 2:47
I think the best way, if you know the keys are all different, is to use the += operator: $array1 += $array2; This appends all the elements of $array2 to the end of $array1.
– David Spector
Nov 10 at 19:49
add a comment |
5
Sounds like you're probably just looking for array_merge.
– Corbin
Nov 1 '12 at 2:47
I think the best way, if you know the keys are all different, is to use the += operator: $array1 += $array2; This appends all the elements of $array2 to the end of $array1.
– David Spector
Nov 10 at 19:49
5
5
Sounds like you're probably just looking for array_merge.
– Corbin
Nov 1 '12 at 2:47
Sounds like you're probably just looking for array_merge.
– Corbin
Nov 1 '12 at 2:47
I think the best way, if you know the keys are all different, is to use the += operator: $array1 += $array2; This appends all the elements of $array2 to the end of $array1.
– David Spector
Nov 10 at 19:49
I think the best way, if you know the keys are all different, is to use the += operator: $array1 += $array2; This appends all the elements of $array2 to the end of $array1.
– David Spector
Nov 10 at 19:49
add a comment |
7 Answers
7
active
oldest
votes
up vote
87
down vote
accepted
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"
}
5
What is benefit of array_merge over using the operator?
– jsteinmann
Nov 1 '12 at 3:01
26
Array Union (+): The + operator appends elements of remaining keys from the right handed array to the left handed, whereas duplicated keys are NOT overwritten. array_merge(): If the input arrays have the same string keys, then the later value for that key will overwrite the previous one. If, however, the arrays contain numeric keys, the later value will not overwrite the original value, but will be appended. If all of the arrays contain only numeric keys, the resulting array is given incrementing keys starting from zero.
– Samuel Cook
Nov 1 '12 at 3:04
10
It should also be noted thatarray_merge
will return NULL if any of the arguments are NULL.
– SeanWM
Mar 6 '14 at 19:07
2
If there are integer keys, then they will be changed to integer keys STARTING from 0. Be very careful with array_merge. Better use a foreach loop to do what you are trying to do.
– user2850305
Dec 8 '17 at 4:35
@user2850305 using the + operator will do the trick
– Benjamin
Feb 26 at 8:25
add a comment |
up vote
20
down vote
Check out array_merge()
.
$array3 = array_merge($array1, $array2);
19
@SudhanshuSaxena Considering I was the first person to post it, I don't see how it could be a repeat answer.
– Brad
Jun 4 '15 at 14:25
2
@SudhanshuSaxena not everyone here is for getting rep or competing...appreciate the efforts taken to help the thread starter.
– Gaurav Pangam
Mar 7 '17 at 6:34
add a comment |
up vote
5
down vote
Another option is array_replace, where an original array is modified by other arrays:
- Same keys will cause subsequent values to overrite the original array
- New keys on subsequent arrays will be created on the original array
This means that the key => value association is preserved and no duplicate keys are inserted.
This is the correct answer. array_merge will not work if you have numeric keys (all keys will be converted to consistent indexes).
– Dmitry Belyaev
Mar 23 '17 at 23:03
add a comment |
up vote
2
down vote
I use a wrapper around array_merge to deal with SeanWM's comment about null arrays; I also sometimes want to get rid of duplicates. I'm also generally wanting to merge one array into another, as opposed to creating a new array. This ends up as:
/**
* Merge two arrays - but if one is blank or not an array, return the other.
* @param $a array First array, into which the second array will be merged
* @param $b array Second array, with the data to be merged
* @param $unique boolean If true, remove duplicate values before returning
*/
function arrayMerge(&$a, $b, $unique = false) {
if (empty($b)) {
return; // No changes to be made to $a
}
if (empty($a)) {
$a = $b;
return;
}
$a = array_merge($a, $b);
if ($unique) {
$a = array_unique($a);
}
}
add a comment |
up vote
0
down vote
I stumbled upon this question trying to identify a clean way to join two assoc arrays.
I was trying to join two different tables that didn't have relationships to each other.
This is what I came up with for PDO Query joining two Tables. Samuel Cook is what identified a solution for me with the array_merge()
+1 to him.
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "SELECT * FROM ".databaseTbl_Residential_Prospects."";
$ResidentialData = $pdo->prepare($sql);
$ResidentialData->execute(array($lapi));
$ResidentialProspects = $ResidentialData->fetchAll(PDO::FETCH_ASSOC);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "SELECT * FROM ".databaseTbl_Commercial_Prospects."";
$CommercialData = $pdo->prepare($sql);
$CommercialData->execute(array($lapi));
$CommercialProspects = $CommercialData->fetchAll(PDO::FETCH_ASSOC);
$Prospects = array_merge($ResidentialProspects,$CommercialProspects);
echo '<pre>';
var_dump($Prospects);
echo '</pre>';
Maybe this will help someone else out.
add a comment |
up vote
0
down vote
I know it's an old question but I'd like to add one more case I had recently with MongoDB driver queries and none of array_merge
, array_replace
nor array_push
worked. I had a bit complex structure of objects wrapped as arrays in array:
$a = [
["a" => [1, "a2"]],
["b" => ["b1", 2]]
];
$t = [
["c" => ["c1", "c2"]],
["b" => ["b1", 2]]
];
And I needed to merge them keeping the same structure like this:
$merged = [
["a" => [1, "a2"]],
["b" => ["b1", 2]],
["c" => ["c1", "c2"]],
["b" => ["b1", 2]]
];
The best solution I came up with was this:
public static function glueArrays($arr1, $arr2) {
// merges TWO (2) arrays without adding indexing.
$myArr = $arr1;
foreach ($arr2 as $arrayItem) {
$myArr = $arrayItem;
}
return $myArr;
}
add a comment |
up vote
0
down vote
$array = array(
22 => true,
25 => true,
34 => true,
35 => true,
);
print_r(
array_replace($array, [
22 => true,
42 => true,
])
);
print_r(
array_merge($array, [
22 => true,
42 => true,
])
);
If it is numeric but not sequential associative array, you need to use array_replace
add a comment |
7 Answers
7
active
oldest
votes
7 Answers
7
active
oldest
votes
active
oldest
votes
active
oldest
votes
up vote
87
down vote
accepted
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"
}
5
What is benefit of array_merge over using the operator?
– jsteinmann
Nov 1 '12 at 3:01
26
Array Union (+): The + operator appends elements of remaining keys from the right handed array to the left handed, whereas duplicated keys are NOT overwritten. array_merge(): If the input arrays have the same string keys, then the later value for that key will overwrite the previous one. If, however, the arrays contain numeric keys, the later value will not overwrite the original value, but will be appended. If all of the arrays contain only numeric keys, the resulting array is given incrementing keys starting from zero.
– Samuel Cook
Nov 1 '12 at 3:04
10
It should also be noted thatarray_merge
will return NULL if any of the arguments are NULL.
– SeanWM
Mar 6 '14 at 19:07
2
If there are integer keys, then they will be changed to integer keys STARTING from 0. Be very careful with array_merge. Better use a foreach loop to do what you are trying to do.
– user2850305
Dec 8 '17 at 4:35
@user2850305 using the + operator will do the trick
– Benjamin
Feb 26 at 8:25
add a comment |
up vote
87
down vote
accepted
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"
}
5
What is benefit of array_merge over using the operator?
– jsteinmann
Nov 1 '12 at 3:01
26
Array Union (+): The + operator appends elements of remaining keys from the right handed array to the left handed, whereas duplicated keys are NOT overwritten. array_merge(): If the input arrays have the same string keys, then the later value for that key will overwrite the previous one. If, however, the arrays contain numeric keys, the later value will not overwrite the original value, but will be appended. If all of the arrays contain only numeric keys, the resulting array is given incrementing keys starting from zero.
– Samuel Cook
Nov 1 '12 at 3:04
10
It should also be noted thatarray_merge
will return NULL if any of the arguments are NULL.
– SeanWM
Mar 6 '14 at 19:07
2
If there are integer keys, then they will be changed to integer keys STARTING from 0. Be very careful with array_merge. Better use a foreach loop to do what you are trying to do.
– user2850305
Dec 8 '17 at 4:35
@user2850305 using the + operator will do the trick
– Benjamin
Feb 26 at 8:25
add a comment |
up vote
87
down vote
accepted
up vote
87
down vote
accepted
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"
}
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"
}
edited Nov 21 at 19:41
Mohamad Hamouday
32748
32748
answered Nov 1 '12 at 2:50
Samuel Cook
13.2k43650
13.2k43650
5
What is benefit of array_merge over using the operator?
– jsteinmann
Nov 1 '12 at 3:01
26
Array Union (+): The + operator appends elements of remaining keys from the right handed array to the left handed, whereas duplicated keys are NOT overwritten. array_merge(): If the input arrays have the same string keys, then the later value for that key will overwrite the previous one. If, however, the arrays contain numeric keys, the later value will not overwrite the original value, but will be appended. If all of the arrays contain only numeric keys, the resulting array is given incrementing keys starting from zero.
– Samuel Cook
Nov 1 '12 at 3:04
10
It should also be noted thatarray_merge
will return NULL if any of the arguments are NULL.
– SeanWM
Mar 6 '14 at 19:07
2
If there are integer keys, then they will be changed to integer keys STARTING from 0. Be very careful with array_merge. Better use a foreach loop to do what you are trying to do.
– user2850305
Dec 8 '17 at 4:35
@user2850305 using the + operator will do the trick
– Benjamin
Feb 26 at 8:25
add a comment |
5
What is benefit of array_merge over using the operator?
– jsteinmann
Nov 1 '12 at 3:01
26
Array Union (+): The + operator appends elements of remaining keys from the right handed array to the left handed, whereas duplicated keys are NOT overwritten. array_merge(): If the input arrays have the same string keys, then the later value for that key will overwrite the previous one. If, however, the arrays contain numeric keys, the later value will not overwrite the original value, but will be appended. If all of the arrays contain only numeric keys, the resulting array is given incrementing keys starting from zero.
– Samuel Cook
Nov 1 '12 at 3:04
10
It should also be noted thatarray_merge
will return NULL if any of the arguments are NULL.
– SeanWM
Mar 6 '14 at 19:07
2
If there are integer keys, then they will be changed to integer keys STARTING from 0. Be very careful with array_merge. Better use a foreach loop to do what you are trying to do.
– user2850305
Dec 8 '17 at 4:35
@user2850305 using the + operator will do the trick
– Benjamin
Feb 26 at 8:25
5
5
What is benefit of array_merge over using the operator?
– jsteinmann
Nov 1 '12 at 3:01
What is benefit of array_merge over using the operator?
– jsteinmann
Nov 1 '12 at 3:01
26
26
Array Union (+): The + operator appends elements of remaining keys from the right handed array to the left handed, whereas duplicated keys are NOT overwritten. array_merge(): If the input arrays have the same string keys, then the later value for that key will overwrite the previous one. If, however, the arrays contain numeric keys, the later value will not overwrite the original value, but will be appended. If all of the arrays contain only numeric keys, the resulting array is given incrementing keys starting from zero.
– Samuel Cook
Nov 1 '12 at 3:04
Array Union (+): The + operator appends elements of remaining keys from the right handed array to the left handed, whereas duplicated keys are NOT overwritten. array_merge(): If the input arrays have the same string keys, then the later value for that key will overwrite the previous one. If, however, the arrays contain numeric keys, the later value will not overwrite the original value, but will be appended. If all of the arrays contain only numeric keys, the resulting array is given incrementing keys starting from zero.
– Samuel Cook
Nov 1 '12 at 3:04
10
10
It should also be noted that
array_merge
will return NULL if any of the arguments are NULL.– SeanWM
Mar 6 '14 at 19:07
It should also be noted that
array_merge
will return NULL if any of the arguments are NULL.– SeanWM
Mar 6 '14 at 19:07
2
2
If there are integer keys, then they will be changed to integer keys STARTING from 0. Be very careful with array_merge. Better use a foreach loop to do what you are trying to do.
– user2850305
Dec 8 '17 at 4:35
If there are integer keys, then they will be changed to integer keys STARTING from 0. Be very careful with array_merge. Better use a foreach loop to do what you are trying to do.
– user2850305
Dec 8 '17 at 4:35
@user2850305 using the + operator will do the trick
– Benjamin
Feb 26 at 8:25
@user2850305 using the + operator will do the trick
– Benjamin
Feb 26 at 8:25
add a comment |
up vote
20
down vote
Check out array_merge()
.
$array3 = array_merge($array1, $array2);
19
@SudhanshuSaxena Considering I was the first person to post it, I don't see how it could be a repeat answer.
– Brad
Jun 4 '15 at 14:25
2
@SudhanshuSaxena not everyone here is for getting rep or competing...appreciate the efforts taken to help the thread starter.
– Gaurav Pangam
Mar 7 '17 at 6:34
add a comment |
up vote
20
down vote
Check out array_merge()
.
$array3 = array_merge($array1, $array2);
19
@SudhanshuSaxena Considering I was the first person to post it, I don't see how it could be a repeat answer.
– Brad
Jun 4 '15 at 14:25
2
@SudhanshuSaxena not everyone here is for getting rep or competing...appreciate the efforts taken to help the thread starter.
– Gaurav Pangam
Mar 7 '17 at 6:34
add a comment |
up vote
20
down vote
up vote
20
down vote
Check out array_merge()
.
$array3 = array_merge($array1, $array2);
Check out array_merge()
.
$array3 = array_merge($array1, $array2);
answered Nov 1 '12 at 2:47
Brad
113k26226386
113k26226386
19
@SudhanshuSaxena Considering I was the first person to post it, I don't see how it could be a repeat answer.
– Brad
Jun 4 '15 at 14:25
2
@SudhanshuSaxena not everyone here is for getting rep or competing...appreciate the efforts taken to help the thread starter.
– Gaurav Pangam
Mar 7 '17 at 6:34
add a comment |
19
@SudhanshuSaxena Considering I was the first person to post it, I don't see how it could be a repeat answer.
– Brad
Jun 4 '15 at 14:25
2
@SudhanshuSaxena not everyone here is for getting rep or competing...appreciate the efforts taken to help the thread starter.
– Gaurav Pangam
Mar 7 '17 at 6:34
19
19
@SudhanshuSaxena Considering I was the first person to post it, I don't see how it could be a repeat answer.
– Brad
Jun 4 '15 at 14:25
@SudhanshuSaxena Considering I was the first person to post it, I don't see how it could be a repeat answer.
– Brad
Jun 4 '15 at 14:25
2
2
@SudhanshuSaxena not everyone here is for getting rep or competing...appreciate the efforts taken to help the thread starter.
– Gaurav Pangam
Mar 7 '17 at 6:34
@SudhanshuSaxena not everyone here is for getting rep or competing...appreciate the efforts taken to help the thread starter.
– Gaurav Pangam
Mar 7 '17 at 6:34
add a comment |
up vote
5
down vote
Another option is array_replace, where an original array is modified by other arrays:
- Same keys will cause subsequent values to overrite the original array
- New keys on subsequent arrays will be created on the original array
This means that the key => value association is preserved and no duplicate keys are inserted.
This is the correct answer. array_merge will not work if you have numeric keys (all keys will be converted to consistent indexes).
– Dmitry Belyaev
Mar 23 '17 at 23:03
add a comment |
up vote
5
down vote
Another option is array_replace, where an original array is modified by other arrays:
- Same keys will cause subsequent values to overrite the original array
- New keys on subsequent arrays will be created on the original array
This means that the key => value association is preserved and no duplicate keys are inserted.
This is the correct answer. array_merge will not work if you have numeric keys (all keys will be converted to consistent indexes).
– Dmitry Belyaev
Mar 23 '17 at 23:03
add a comment |
up vote
5
down vote
up vote
5
down vote
Another option is array_replace, where an original array is modified by other arrays:
- Same keys will cause subsequent values to overrite the original array
- New keys on subsequent arrays will be created on the original array
This means that the key => value association is preserved and no duplicate keys are inserted.
Another option is array_replace, where an original array is modified by other arrays:
- Same keys will cause subsequent values to overrite the original array
- New keys on subsequent arrays will be created on the original array
This means that the key => value association is preserved and no duplicate keys are inserted.
edited Mar 24 '17 at 14:39
answered Jan 27 '17 at 19:33
wranvaud
7171014
7171014
This is the correct answer. array_merge will not work if you have numeric keys (all keys will be converted to consistent indexes).
– Dmitry Belyaev
Mar 23 '17 at 23:03
add a comment |
This is the correct answer. array_merge will not work if you have numeric keys (all keys will be converted to consistent indexes).
– Dmitry Belyaev
Mar 23 '17 at 23:03
This is the correct answer. array_merge will not work if you have numeric keys (all keys will be converted to consistent indexes).
– Dmitry Belyaev
Mar 23 '17 at 23:03
This is the correct answer. array_merge will not work if you have numeric keys (all keys will be converted to consistent indexes).
– Dmitry Belyaev
Mar 23 '17 at 23:03
add a comment |
up vote
2
down vote
I use a wrapper around array_merge to deal with SeanWM's comment about null arrays; I also sometimes want to get rid of duplicates. I'm also generally wanting to merge one array into another, as opposed to creating a new array. This ends up as:
/**
* Merge two arrays - but if one is blank or not an array, return the other.
* @param $a array First array, into which the second array will be merged
* @param $b array Second array, with the data to be merged
* @param $unique boolean If true, remove duplicate values before returning
*/
function arrayMerge(&$a, $b, $unique = false) {
if (empty($b)) {
return; // No changes to be made to $a
}
if (empty($a)) {
$a = $b;
return;
}
$a = array_merge($a, $b);
if ($unique) {
$a = array_unique($a);
}
}
add a comment |
up vote
2
down vote
I use a wrapper around array_merge to deal with SeanWM's comment about null arrays; I also sometimes want to get rid of duplicates. I'm also generally wanting to merge one array into another, as opposed to creating a new array. This ends up as:
/**
* Merge two arrays - but if one is blank or not an array, return the other.
* @param $a array First array, into which the second array will be merged
* @param $b array Second array, with the data to be merged
* @param $unique boolean If true, remove duplicate values before returning
*/
function arrayMerge(&$a, $b, $unique = false) {
if (empty($b)) {
return; // No changes to be made to $a
}
if (empty($a)) {
$a = $b;
return;
}
$a = array_merge($a, $b);
if ($unique) {
$a = array_unique($a);
}
}
add a comment |
up vote
2
down vote
up vote
2
down vote
I use a wrapper around array_merge to deal with SeanWM's comment about null arrays; I also sometimes want to get rid of duplicates. I'm also generally wanting to merge one array into another, as opposed to creating a new array. This ends up as:
/**
* Merge two arrays - but if one is blank or not an array, return the other.
* @param $a array First array, into which the second array will be merged
* @param $b array Second array, with the data to be merged
* @param $unique boolean If true, remove duplicate values before returning
*/
function arrayMerge(&$a, $b, $unique = false) {
if (empty($b)) {
return; // No changes to be made to $a
}
if (empty($a)) {
$a = $b;
return;
}
$a = array_merge($a, $b);
if ($unique) {
$a = array_unique($a);
}
}
I use a wrapper around array_merge to deal with SeanWM's comment about null arrays; I also sometimes want to get rid of duplicates. I'm also generally wanting to merge one array into another, as opposed to creating a new array. This ends up as:
/**
* Merge two arrays - but if one is blank or not an array, return the other.
* @param $a array First array, into which the second array will be merged
* @param $b array Second array, with the data to be merged
* @param $unique boolean If true, remove duplicate values before returning
*/
function arrayMerge(&$a, $b, $unique = false) {
if (empty($b)) {
return; // No changes to be made to $a
}
if (empty($a)) {
$a = $b;
return;
}
$a = array_merge($a, $b);
if ($unique) {
$a = array_unique($a);
}
}
answered Sep 29 '15 at 10:01
xgretsch
801912
801912
add a comment |
add a comment |
up vote
0
down vote
I stumbled upon this question trying to identify a clean way to join two assoc arrays.
I was trying to join two different tables that didn't have relationships to each other.
This is what I came up with for PDO Query joining two Tables. Samuel Cook is what identified a solution for me with the array_merge()
+1 to him.
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "SELECT * FROM ".databaseTbl_Residential_Prospects."";
$ResidentialData = $pdo->prepare($sql);
$ResidentialData->execute(array($lapi));
$ResidentialProspects = $ResidentialData->fetchAll(PDO::FETCH_ASSOC);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "SELECT * FROM ".databaseTbl_Commercial_Prospects."";
$CommercialData = $pdo->prepare($sql);
$CommercialData->execute(array($lapi));
$CommercialProspects = $CommercialData->fetchAll(PDO::FETCH_ASSOC);
$Prospects = array_merge($ResidentialProspects,$CommercialProspects);
echo '<pre>';
var_dump($Prospects);
echo '</pre>';
Maybe this will help someone else out.
add a comment |
up vote
0
down vote
I stumbled upon this question trying to identify a clean way to join two assoc arrays.
I was trying to join two different tables that didn't have relationships to each other.
This is what I came up with for PDO Query joining two Tables. Samuel Cook is what identified a solution for me with the array_merge()
+1 to him.
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "SELECT * FROM ".databaseTbl_Residential_Prospects."";
$ResidentialData = $pdo->prepare($sql);
$ResidentialData->execute(array($lapi));
$ResidentialProspects = $ResidentialData->fetchAll(PDO::FETCH_ASSOC);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "SELECT * FROM ".databaseTbl_Commercial_Prospects."";
$CommercialData = $pdo->prepare($sql);
$CommercialData->execute(array($lapi));
$CommercialProspects = $CommercialData->fetchAll(PDO::FETCH_ASSOC);
$Prospects = array_merge($ResidentialProspects,$CommercialProspects);
echo '<pre>';
var_dump($Prospects);
echo '</pre>';
Maybe this will help someone else out.
add a comment |
up vote
0
down vote
up vote
0
down vote
I stumbled upon this question trying to identify a clean way to join two assoc arrays.
I was trying to join two different tables that didn't have relationships to each other.
This is what I came up with for PDO Query joining two Tables. Samuel Cook is what identified a solution for me with the array_merge()
+1 to him.
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "SELECT * FROM ".databaseTbl_Residential_Prospects."";
$ResidentialData = $pdo->prepare($sql);
$ResidentialData->execute(array($lapi));
$ResidentialProspects = $ResidentialData->fetchAll(PDO::FETCH_ASSOC);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "SELECT * FROM ".databaseTbl_Commercial_Prospects."";
$CommercialData = $pdo->prepare($sql);
$CommercialData->execute(array($lapi));
$CommercialProspects = $CommercialData->fetchAll(PDO::FETCH_ASSOC);
$Prospects = array_merge($ResidentialProspects,$CommercialProspects);
echo '<pre>';
var_dump($Prospects);
echo '</pre>';
Maybe this will help someone else out.
I stumbled upon this question trying to identify a clean way to join two assoc arrays.
I was trying to join two different tables that didn't have relationships to each other.
This is what I came up with for PDO Query joining two Tables. Samuel Cook is what identified a solution for me with the array_merge()
+1 to him.
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "SELECT * FROM ".databaseTbl_Residential_Prospects."";
$ResidentialData = $pdo->prepare($sql);
$ResidentialData->execute(array($lapi));
$ResidentialProspects = $ResidentialData->fetchAll(PDO::FETCH_ASSOC);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "SELECT * FROM ".databaseTbl_Commercial_Prospects."";
$CommercialData = $pdo->prepare($sql);
$CommercialData->execute(array($lapi));
$CommercialProspects = $CommercialData->fetchAll(PDO::FETCH_ASSOC);
$Prospects = array_merge($ResidentialProspects,$CommercialProspects);
echo '<pre>';
var_dump($Prospects);
echo '</pre>';
Maybe this will help someone else out.
answered Feb 20 '17 at 2:41
Kray
402620
402620
add a comment |
add a comment |
up vote
0
down vote
I know it's an old question but I'd like to add one more case I had recently with MongoDB driver queries and none of array_merge
, array_replace
nor array_push
worked. I had a bit complex structure of objects wrapped as arrays in array:
$a = [
["a" => [1, "a2"]],
["b" => ["b1", 2]]
];
$t = [
["c" => ["c1", "c2"]],
["b" => ["b1", 2]]
];
And I needed to merge them keeping the same structure like this:
$merged = [
["a" => [1, "a2"]],
["b" => ["b1", 2]],
["c" => ["c1", "c2"]],
["b" => ["b1", 2]]
];
The best solution I came up with was this:
public static function glueArrays($arr1, $arr2) {
// merges TWO (2) arrays without adding indexing.
$myArr = $arr1;
foreach ($arr2 as $arrayItem) {
$myArr = $arrayItem;
}
return $myArr;
}
add a comment |
up vote
0
down vote
I know it's an old question but I'd like to add one more case I had recently with MongoDB driver queries and none of array_merge
, array_replace
nor array_push
worked. I had a bit complex structure of objects wrapped as arrays in array:
$a = [
["a" => [1, "a2"]],
["b" => ["b1", 2]]
];
$t = [
["c" => ["c1", "c2"]],
["b" => ["b1", 2]]
];
And I needed to merge them keeping the same structure like this:
$merged = [
["a" => [1, "a2"]],
["b" => ["b1", 2]],
["c" => ["c1", "c2"]],
["b" => ["b1", 2]]
];
The best solution I came up with was this:
public static function glueArrays($arr1, $arr2) {
// merges TWO (2) arrays without adding indexing.
$myArr = $arr1;
foreach ($arr2 as $arrayItem) {
$myArr = $arrayItem;
}
return $myArr;
}
add a comment |
up vote
0
down vote
up vote
0
down vote
I know it's an old question but I'd like to add one more case I had recently with MongoDB driver queries and none of array_merge
, array_replace
nor array_push
worked. I had a bit complex structure of objects wrapped as arrays in array:
$a = [
["a" => [1, "a2"]],
["b" => ["b1", 2]]
];
$t = [
["c" => ["c1", "c2"]],
["b" => ["b1", 2]]
];
And I needed to merge them keeping the same structure like this:
$merged = [
["a" => [1, "a2"]],
["b" => ["b1", 2]],
["c" => ["c1", "c2"]],
["b" => ["b1", 2]]
];
The best solution I came up with was this:
public static function glueArrays($arr1, $arr2) {
// merges TWO (2) arrays without adding indexing.
$myArr = $arr1;
foreach ($arr2 as $arrayItem) {
$myArr = $arrayItem;
}
return $myArr;
}
I know it's an old question but I'd like to add one more case I had recently with MongoDB driver queries and none of array_merge
, array_replace
nor array_push
worked. I had a bit complex structure of objects wrapped as arrays in array:
$a = [
["a" => [1, "a2"]],
["b" => ["b1", 2]]
];
$t = [
["c" => ["c1", "c2"]],
["b" => ["b1", 2]]
];
And I needed to merge them keeping the same structure like this:
$merged = [
["a" => [1, "a2"]],
["b" => ["b1", 2]],
["c" => ["c1", "c2"]],
["b" => ["b1", 2]]
];
The best solution I came up with was this:
public static function glueArrays($arr1, $arr2) {
// merges TWO (2) arrays without adding indexing.
$myArr = $arr1;
foreach ($arr2 as $arrayItem) {
$myArr = $arrayItem;
}
return $myArr;
}
edited Apr 11 at 6:10
answered Apr 10 at 17:51
JohnPan
574315
574315
add a comment |
add a comment |
up vote
0
down vote
$array = array(
22 => true,
25 => true,
34 => true,
35 => true,
);
print_r(
array_replace($array, [
22 => true,
42 => true,
])
);
print_r(
array_merge($array, [
22 => true,
42 => true,
])
);
If it is numeric but not sequential associative array, you need to use array_replace
add a comment |
up vote
0
down vote
$array = array(
22 => true,
25 => true,
34 => true,
35 => true,
);
print_r(
array_replace($array, [
22 => true,
42 => true,
])
);
print_r(
array_merge($array, [
22 => true,
42 => true,
])
);
If it is numeric but not sequential associative array, you need to use array_replace
add a comment |
up vote
0
down vote
up vote
0
down vote
$array = array(
22 => true,
25 => true,
34 => true,
35 => true,
);
print_r(
array_replace($array, [
22 => true,
42 => true,
])
);
print_r(
array_merge($array, [
22 => true,
42 => true,
])
);
If it is numeric but not sequential associative array, you need to use array_replace
$array = array(
22 => true,
25 => true,
34 => true,
35 => true,
);
print_r(
array_replace($array, [
22 => true,
42 => true,
])
);
print_r(
array_merge($array, [
22 => true,
42 => true,
])
);
If it is numeric but not sequential associative array, you need to use array_replace
answered Jun 6 at 3:41
tom10271
1,17731831
1,17731831
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Some of your past answers have not been well-received, and you're in danger of being blocked from answering.
Please pay close attention to the following guidance:
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f13170230%2fphp-combine-two-associative-arrays-into-one-array%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
5
Sounds like you're probably just looking for array_merge.
– Corbin
Nov 1 '12 at 2:47
I think the best way, if you know the keys are all different, is to use the += operator: $array1 += $array2; This appends all the elements of $array2 to the end of $array1.
– David Spector
Nov 10 at 19:49