This question already has answers here:
Merge row data from multiple arrays
(6 answers)
Closed 5 months ago.
Having some difficulty trying to merge two arrays with the same numeric key. I have tried array_merge() and array_merge_recursive(), but all that seems to do is append the second array.
The first array has the following form:
Array
(
[384] => Array
(
[name] => SomeMovieName1
[age] => 12.2 hrs
[IMDBLink] =>
[IMDBRating] =>
[coverArt] =>
)
[452] => Array
(
[name] => SomeMovieName2
[age] => 13.1 hrs
[IMDBLink] =>
[IMDBRating] =>
[coverArt] =>
)
[945] => Array
(
[name] => SomeMovieName3
[age] => 13.6 hrs
[IMDBLink] =>
[IMDBRating] =>
[coverArt] =>
)
)
And here is the second array I want to combine/merge with the first:
Array
(
[384] => Array
(
[IMDBRating] => 7.2
[IMDBLink] => http://www.imdb.com/LinkToMovie1
[coverArt] => http://www.SomeLinkToCoverArt.com/1
)
[452] => Array
(
[IMDBRating] => 8.2
[IMDBLink] => http://www.imdb.com/LinkToMovie2
[coverArt] => http://www.SomeLinkToCoverArt.com/2
)
[945] => Array
(
[IMDBRating] => 6.2
[IMDBLink] => http://www.imdb.com/LinkToMovie3
[coverArt] => http://www.SomeLinkToCoverArt.com/3
)
)
And after merging, I would like the result to be:
Array
(
[0] => Array
(
[name] => SomeMovieName1
[age] => 12.2 hrs
[IMDBRating] => 7.2
[IMDBLink] => http://www.imdb.com/LinkToMovie1
[coverArt] => http://www.SomeLinkToCoverArt.com/1
)
[1] => Array
(
[name] => SomeMovieName2
[age] => 13.1 hrs
[IMDBRating] => 8.2
[IMDBLink] => http://www.imdb.com/LinkToMovie2
[coverArt] => http://www.SomeLinkToCoverArt.com/2
)
[2] => Array
(
[name] => SomeMovieName3
[age] => 13.6 hrs
[IMDBRating] => 6.2
[IMDBLink] => http://www.imdb.com/LinkToMovie3
[coverArt] => http://www.SomeLinkToCoverArt.com/3
)
)
Not sure if it's because of the inner arrays causing an issue that it won't work directly with array_merge() or array_merge_recursive(). Any help would be appreciated,
Thanks.
You can try below code to merge array. Code generates desired output required to you. I have used sample array as given by you:
<?php
$arr1=array(
"384"=>array("name"=>"SomeMovieName1","age"=>"12.2 hrs","IMDBLink"=>"","IMDBRating"=>"", "coverArt"=>""),
"452"=>array("name"=>"SomeMovieName2","age"=>"15.2 hrs","IMDBLink"=>"","IMDBRating"=>"", "coverArt"=>""),
"954"=>array("name"=>"SomeMovieName3","age"=>"4.2 hrs","IMDBLink"=>"","IMDBRating"=>"", "coverArt"=>"")
);
$arr2=array(
"384" => array("IMDBLink" => "7.2", "IMDBRating" => "http://www.imdb.com/LinkToMovie1", "coverArt" => "http://www.SomeLinkToCoverArt.com/1"),
"452" => array("IMDBLink" => "5","IMDBRating" => "http://www.imdb.com/LinkToMovie2", "coverArt" => "http://www.SomeLinkToCoverArt.com/2"),
"954"=>array("IMDBLink" => "8","IMDBRating" => "http://www.imdb.com/LinkToMovie3", "coverArt" => "http://www.SomeLinkToCoverArt.com/3")
);
$arr3 = array();
foreach($arr1 as $key=>$val)
{
$arr3[] = array_merge($val, $arr2[$key]);
}
echo "<pre>";
print_r($arr3);
?>
array_merge_recursive doesn't work because your outer array has numeric keys, not string keys. When array_merge or array_merge_recursive are given numeric arrays, they append them rather than merging elements with the same keys.
Instead, you can map through the arrays and merge the corresponding elements.
$result = array_map('array_merge', $array1, $array2);
Note that this code assumes that the two input arrays have all the same keys in the same order. If they're not in the same order, you can use ksort on them first to rearrange them.
If they can have different keys, though, you need a different solution, like the loop in Webang's answer.
It might be easier to run your arrays in a foreach loop and just insert each value into your initial array. Lets call the first array $myFirstArray and the second array $mySecondArray:
foreach ($myFirstArray as $key => $value)
{
$myFirstArray[$key][IMDBRating] = $mySecondArray[$key][IMDBRating];
$myFirstArray[$key][IMDBLink] = $mySecondArray[$key][IMDBLink];
$myFirstArray[$key][coverArt] = $mySecondArray[$key][coverArt];
}
Didn't test this, but it should work:
Call your first array $ar1, and second $ar2
$result=array();
foreach($ar1 as $k=>$v)
{
//if there is a corresponding array2 element
if( isset($ar2[$k]) ){
$result[] = array( $v['name], $v['age'], $ar2[$k]['IMDBLink'], $ar2[$k]['IMDBRating'],$ar2['coverArt']);
}
}
//result
print_r($result);
Related
Question :
I have one array have two key or more split into two or more create array based on array in php.
my Array :
array
(
[RAJAHMUNDRY] => Array
(
[unspcp_code] => 46182005
[title] => 3M™ Half Face Reusable Respirator HF-52 with Holder 1700 And Filter 1744
[total] => 2
[head_quarter] => RAJAHMUNDRY
[0] => 2
)
[HYDERABAD] => Array
(
[unspcp_code] => 46182005
[title] => 3M™ 6200 HALF FACE MASK WITH 7093 FILTER
[total] => 2
[head_quarter] => HYDERABAD
[0] => 2
)
)
I want output like this :
output:
array
(
[RAJAHMUNDRY] => Array
(
[unspcp_code] => 46182005
[title] => 3M™ Half Face Reusable Respirator HF-52 with Holder 1700 And Filter 1744
[total] => 2
[head_quarter] => RAJAHMUNDRY
[0] => 2
)
)
)
array(
[HYDERABAD] => Array
(
[unspcp_code] => 46182005
[title] => 3M™ 6200 HALF FACE MASK WITH 7093 FILTER
[total] => 2
[head_quarter] => HYDERABAD
[0] => 2
)
)
I am not sure how you want to store those arrays, but let me help you.
I assume you have a datastructure like this, so one array with multiple values.
array (
key1 => ...values...,
key2 => ...values...,
...
key_n => ...values...
)
And you want something like this, si multiple arrays with single keys well you need to store that array somehow.
array (
key1 => ...values...
)
array (
key2 => ...values...
)
...
array (
key_n => ...values...
)
If you do not know the exact number of arrays, you can't $array1, $array2, ... $array_n and it also not efficent, so you shoudl have an array of arrays. So something like this:
array(
array (
key1 => ...values...
)
array (
key2 => ...values...
)
...
array (
key_n => ...values...
)
)
So you should iterate trough the keys of the input array and then
So the code
<?php
//example input array
$arr = array (
"key1" => "val1",
"key2" => "val2"
);
$keys = array_keys($arr); //get the keys of the input array, see phpdoc
$output = [];
foreach($keys as $key) {
$output[] = array ($arr[$key]);
}
?>
This will output an array of arrays, with single key of the inner array.
If this is not you answer, reply.
Research:
https://www.php.net/manual/en/function.array-keys.php
https://www.php.net/manual/en/control-structures.foreach.php
php.net - arrays manual Example #6 Accessing array elements
Maybe this document will help you
This may also help you
<?php
$stdArray = array(
"foo" => "bar",
42 => 24,
"dimensional" => array(
"fname" => "jon",
"lname" => "doe",
),
"multi" => array(
"RAJAHMUNDRY" => array(
"unspcp_code" => 46182005,
"head_quarter" => "RAJAHMUNDRY",
0 => 2
),
"HYDERABAD" => array(
"unspcp_code" => 46182005,
"head_quarter" => "HYDERABAD",
0 => 2
),
)
);
print_r($stdArray);
print_r($stdArray["multi"]);
print_r($stdArray["multi"]["RAJAHMUNDRY"]);
This question already has answers here:
Array merge on key of two associative arrays in php?
(2 answers)
Closed 9 months ago.
I have two arrays that need to be merged. I can loop through each array and merge manually. But, Is there a built in function to do this?
Array 1:
Array
(
[0] => Array
(
[detail_image_id] => 6389
[product_name] => Starter broadband Package
)
[1] => Array
(
[detail_image_id] => 6358
[product_name] => Starter broadband Package
)
)
Array 2:
Array
(
[0] => Array
(
[detail_image_id] => 6358
[guid] => http://xxx/wp-content/uploads/2018/04/broadband-4mbs-wingle.jpg
)
[1] => Array
(
[detail_image_id] => 6389
[guid] => http://xxx/wp-content/uploads/2018/04/broadband-4mbs-charji.jpg
)
)
Expected Output array is:
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
)
)
I have added only a sample from the array. Array is huge. Is there any PHP functions like array_merge() or array_map() that we can use instead of manual for loops and iterators?
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',
),
)
You can do something like:
$arr1 = array(); //Your array 1
$arr2 = array(); //Your array 2
//Make a temp array to that use detail_image_id as the key
$arr1Temp = array_combine( array_column($arr1,'detail_image_id'), $arr1 );
$arr2Temp = array_combine( array_column($arr2,'detail_image_id'), $arr2 );
//Get All unique detail_image_id from 2 arrays.
//This is to make sure that all detail_image_id's will be included.
//detail_image_id on 2nd array might not be present on the 1st one
$imgIds = array_unique(array_merge( array_keys($arr1Temp), array_keys($arr2Temp) ));
//Do a simple foreach loop
$result = array();
foreach( $imgIds as $val ) {
$result[] = array_merge( $arr1Temp[$val], $arr2Temp[$val] );
}
print_r( $result );
This will result to:
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
)
)
You can use a combination of array_column() and array_combine() to create a reference array using the detail_image_id as key. Then, with a foreach() loop, you can merge arrays using + operator:
$array1 = [
['detail_image_id' => '6389', 'product_name' => 'Starter broadband Package'],
['detail_image_id' => '6358', 'product_name' => 'Starter broadband Package']
];
$array2 = [
['detail_image_id' => '6358', 'guid' => 'http://xxx/wp-content/uploads/2018/04/broadband-4mbs-wingle.jpg'],
['detail_image_id' => '6389', 'guid' => 'http://xxx/wp-content/uploads/2018/04/broadband-4mbs-charji.jpg']
];
// create associative array with detail_image_id as key,
$out = array_combine(array_column($array1, 'detail_image_id'), $array1);
foreach ($array2 as $item) {
$key = $item['detail_image_id']; // shortcut for the key,
$out[$key] = $out[$key] + $item; // merge arrays
}
print_r(array_values($out)); // reset to indexed keys (0,1,2...)
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
)
)
Below is the print_r($result) result of an $result = array_merge(array($id => $value), array($user => $value), array("Information" => $value)) variable in a piece of PHP code:
Array ( [id] => 1 [user] => 1
[Information] => Array ( [0] => Array ( [name] => 'John' )
[1] => Array ( [family] => 'Goldenberg' )
[2] => Array ( [age] => '21' )))
How to remove the array keys from the "Information" => $value array in PHP to make the output like below:
Array ( [id] => 1 [user] => 1
[Information] => Array ([name] => 'John'
[family] => 'Goldenberg'
[age] => '21'))
Is there any specific function in PHP to complete this task? Thanks a lot for your help.
Your "Information" array is a multidimensional one, having some arrays as the elements, in which there are some "key-value" pairs as "data". You may use the following to reinsert the "data" in the desirable way:
<?php
$info = array( array('name'=>'John'), array('family' => 'Goldenberg'), array('age' => 21));
$out = array();
foreach($info as $arr)
foreach($arr as $key => $val)
$out[$key] = $val;
print_r($out);
?>
Using PHP I need to merge 2 arrays (of equal length into one associative array) here is an excerpt from my current data set:
[1] => Array
(
[0] => C28
[1] => C29
)
[2] => Array
(
[0] => 1AB010050093
[1] => 1AB008140029
)
both elements [1] and [2] are actually a lot longer than just 2 sub-elements (like I said, this is an excerpt).
The deal is that "C28" in the first array corresponds to "1AB010050093" in the second array, and so on... The result I need is to create a new associative array that looks like this:
[1] => Array
(
['ref'] => C28
['part'] => 1AB010050093
)
[2] => Array
(
['ref'] => C29
['part'] => 1AB008140029
)
and so on...
If you are willing to compromise with an array structure like this:
array(
'C28' => '1AB010050093',
'C29' => '1AB008140029'
);
Then you can use the array_combine() (Codepad Demo):
array_combine($refNumbers, $partIds);
Otherwise, you'll need to use a foreach (Codepad Demo):
$combined = array();
foreach($refNumbers as $index => $refNumber) {
if(!array_key_exists($index, $partIds)) {
throw OutOfBoundsException();
}
$combined[] = array(
'ref' => $refNumber,
'part' => $partIds[$index]
);
}
If you're using PHP 5.5+, there is a new method called array_column(), which will get all of the values in a particular column. That could potentially be used, although I think just a simple foreach loop will probably still be your best bet.
How about:
$arr1 = array(
0 => 'C28',
1 => 'C29',
);
$arr2 = array(
0 => '1AB010050093',
1 => '1AB008140029',
);
$result = array();
for ($i=0; $i<count($arr1); $i++) {
$result[] = array('ref' => $arr1[$i], 'part' => $arr2[$i]);
}
print_r($result);
ouptut:
[1] => Array
(
[0] => C28
[1] => C29
)
[2] => Array
(
[0] => 1AB010050093
[1] => 1AB008140029
)
I am working in PHP with array iteration.
I have a multidimensional array like this:
Array
(
[1] => stdClass Object
(
[id] => 1
[comments] => Testing the Data
[stream_context_id] => 5
[stream_entity_id] =>
[class_id] => 1
[parent_id] => 0
[learnt_count] =>
[rating_count] =>
[abused_count] =>
[created_by] => 1
[created_datetime] =>
[stream_context] => comments
[name] =>
[upload_path] =>
[uploadby] =>
[upload_time] =>
)
[2] => stdClass Object
(
[id] => 2
[comments] => Testing the Data
[stream_context_id] => 5
[stream_entity_id] =>
[class_id] => 1
[parent_id] => 0
[learnt_count] =>
[rating_count] =>
[abused_count] =>
[created_by] => 1
[created_datetime] =>
[stream_context] => comments
[name] =>
[upload_path] =>
[uploadby] =>
[upload_time] =>
)
)
Here the first index values i.e. 1 and 2 are the ids mentioned in their corresponding arrays.
I want the same multidimensional array with index values a 0 and 1 and so on.. i.e. the usual format of an array.
Don't know if this is what you meant, but maybe...:
$reindexedArray = array_values($yourArray);
If you also want to convert the stdClass objects to arrays, try:
$reindexedAndArrayifiedArray = array_values(array_map(function ($entry) {
return (array)$entry;
}, $yourArray));
Using array_merge() with a blank array - will renumber numeric indexes:
$result = array_merge(Array(), $your_array_here) ;
This does look like a multidimentional array as you have a named array holding objects.
Your array is currently:
$a = array('1'=>Object, '2'=>Object);
Instead of:
$a = array('1'=>array('id'=>'1', 'comment'=>'some comment'), '2'=>array());
$b = array();
foreach($a as $key=>$val){
$b[] = $val;
}