Joining two arrays? [message #174415] |
Fri, 10 June 2011 18:14 |
Mike
Messages: 18 Registered: December 2010
Karma: 0
|
Junior Member |
|
|
How can I combine two 2-dimensional arrays into a single array using a
matching key value. Here's an example:
I have these two arrays:
$arr1 = array(
array('key'=>7, 'first_name'=>'Joe'),
array('key'=>14, 'first_name'=>'Susan')
);
$arr2 = array(
array('key'=>14, 'last_name'=>'Doe'),
array('key'=>7, 'last_name'=>'Anderson')
);
I want to create a second array JOINing the two based on the key
value, giving me:
$resulting_arr = array(
array('key'=>7, 'first_name'=>'Joe','last_name'=>'Anderson'),
array('key'=>14, 'first_name'=>'Susan','last_name'=>'Doe')
);
Thanks!
Mike
|
|
|
Re: Joining two arrays? [message #174419 is a reply to message #174415] |
Fri, 10 June 2011 19:31 |
Luuk
Messages: 329 Registered: September 2010
Karma: 0
|
Senior Member |
|
|
On 10-06-2011 20:14, Mike wrote:
> How can I combine two 2-dimensional arrays into a single array using a
> matching key value. Here's an example:
>
> I have these two arrays:
>
> $arr1 = array(
> array('key'=>7, 'first_name'=>'Joe'),
> array('key'=>14, 'first_name'=>'Susan')
> );
> $arr2 = array(
> array('key'=>14, 'last_name'=>'Doe'),
> array('key'=>7, 'last_name'=>'Anderson')
> );
>
> I want to create a second array JOINing the two based on the key
> value, giving me:
>
> $resulting_arr = array(
> array('key'=>7, 'first_name'=>'Joe','last_name'=>'Anderson'),
> array('key'=>14, 'first_name'=>'Susan','last_name'=>'Doe')
> );
>
> Thanks!
>
> Mike
<?php
$arr1 = array(
array('key'=>7, 'first_name'=>'Joe'),
array('key'=>14, 'first_name'=>'Susan')
);
$arr2 = array(
array('key'=>14, 'last_name'=>'Doe'),
array('key'=>7, 'last_name'=>'Anderson')
);
//print_r($arr1);
//print_r($arr2);
foreach ($arr1 as $key1 => $row) {
$first_name[$row['key']] = $row['first_name'];
}
foreach ($arr2 as $key1 => $row) {
$last_name[$row['key']] = $row['last_name'];
}
//print_r($first_name);
//print_r($last_name);
foreach ($first_name as $key => $value) {
print $key.": ".$first_name[$key]." ".$last_name[$key]."\n";
}
?>
--
Luuk
|
|
|
Re: Joining two arrays? [message #174423 is a reply to message #174415] |
Fri, 10 June 2011 23:10 |
Denis McMahon
Messages: 634 Registered: September 2010
Karma: 0
|
Senior Member |
|
|
On Fri, 10 Jun 2011 11:14:28 -0700, Mike wrote:
> How can I combine two 2-dimensional arrays into a single array using a
> matching key value. Here's an example:
What solution(s) have you tried and what happened?
Rgds
Denis McMahon
|
|
|