TalkPHP

TalkPHP (http://www.talkphp.com/forums.php)
-   General (http://www.talkphp.com/general/)
-   -   Array merge on similar key => value (http://www.talkphp.com/general/5057-array-merge-similar-key-value.html)

delayedinsanity 10-24-2009 03:15 AM

Array merge on similar key => value
 
I have three arrays I'm working with based on queries pulled from a database. All of them have one key => value pair in common, and I'm looking for the most elegant way to merge these arrays.

array_merge() of course won't work, and I'm curious if there's a better solution than iterating through and merging it 'by hand' so to speak within a loop.

For example, the arrays all follow this paradigm;

Code:

Array
(
    [0] => Array
        (
            [timestamp] => 2009-10-23
            [key_one] => value_one
        )

....

Array
(
    [0] => Array
        (
            [timestamp] => 2009-10-23
            [another_key] => another_value

        )

The desired result, is of course;

Code:

Array
(
    [0] => Array
        (
            [timestamp] => 2009-10-23
            [key_one] => value_one
            [another_key] => another_value
        )


tony 10-24-2009 03:23 PM

you could use a combination of intersect, diff, and merge like this:

PHP Code:

<?php
$arr1 
= array(array("timestamp" => "2009-10-23""key_one" => 45));
$arr2 = array(array("timestamp" => "2009-10-23""another_key" => 1234));
print_r($arr1);
echo 
"<br /><br />";
print_r($arr2);
echo 
"<br /><br />";


$identical array_intersect($arr1[0], $arr2[0]);
$diff array_merge(array_diff($arr1[0], $arr2[0]), array_diff($arr2[0], $arr1[0]));
$merge[0] = array_merge($identical$diff);
print_r($merge);
echo 
"<br /><br />";
?>

this solution just takes into account only 2 arrays, but it can be modified to do for multiple.

delayedinsanity 10-24-2009 05:46 PM

Thanks Tony, I wound up just looping through it directly; The above method won't work on the array for me as a whole due to the fact that I'd still have to loop through and merge each key seperately, and trying to run the intersect and diff on the top level of the array doesn't work.

Were I to loop through I'm sure something along the lines of,

PHP Code:

$count count$arr );
for ( 
$i 0$i <= $count$i++ ) {
    
$arr[$i] = array_mergearray_diff$arr[$i], $arr_two[$i] ), array_diff$arr_two[$i..... 

Would do the trick, but it becomes redundant by the time I wind up using a loop. Array-fu!

I'm a huge fan of array_s(p)?lice, array_search, et al, but there's some I've never had the chance to use yet and it was nice to play with them a little. :)


All times are GMT. The time now is 11:07 AM.

Powered by vBulletin® Version 3.6.8
Copyright ©2000 - 2013, Jelsoft Enterprises Ltd.
Search Engine Optimization by vBSEO 3.1.0