Jump to content

Help Comparing Array Diffs and Inserting Entries


aa411853

Recommended Posts

Ok, I've got 2 arrays that I need to compare and then insert extra elements if necessary.

 

Array 1

 

Array ( 
[0] => Array ( [dt] => Apr-10 [total_posts] => 20 [ind_posts] => 20 ) 
[1] => Array ( [dt] => May-10 [total_posts] => 5 [ind_posts] => 5 ) 
[2] => Array ( [dt] => Jun-10 [total_posts] => 56 [ind_posts] => 54 ) 
[3] => Array ( [dt] => Jul-10 [total_posts] => 13 [ind_posts] => 7 )
) 

Array 2

 

Array ( 
[0] => Array ( [dt] => Jun-10 [total_posts] => 20 [ind_posts] => 20 ) 
[1] => Array ( [dt] => Jul-10 [total_posts] => 5 [ind_posts] => 5 ) 
) 

 

So in this example, what I need to do is compare the two arrays, see which months are missing, and then add the extra elements like so:

 

Array 2

Array ( 
[0] => Array ( [dt] => Apr-10 [total_posts] => 0 [ind_posts] => 0 ) 
[1] => Array ( [dt] => May-10 [total_posts] => 0 [ind_posts] => 0 ) 
[2] => Array ( [dt] => Jun-10 [total_posts] => 20 [ind_posts] => 20 ) 
[3] => Array ( [dt] => Jul-10 [total_posts] => 5 [ind_posts] => 5 ) 
) 

 

Array 1 is my primary array and I need to insert extra elements into array 2 if array 2 doesn't include all the same [dt] elements. 

 

I'm lost as to how to even start this.  Comparing the two arrays is easy, but I'm just not sure how to modify array 2.

 

There's got to be a more elegant way to do it, but I'll have to test something later.  Here is the obvious:

 

foreach($array1 as $a1) {
$add = true;
foreach($array2 as $a2) {
	if(in_array($a1['dt'], $a2)) {
		$add = false;
		break;
	}
}
if($add) {
	$array2[] = $a1;
}
}

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.