aa411853 Posted July 17, 2010 Share Posted July 17, 2010 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. Link to comment https://forums.phpfreaks.com/topic/208032-help-comparing-array-diffs-and-inserting-entries/ Share on other sites More sharing options...
AbraCadaver Posted July 17, 2010 Share Posted July 17, 2010 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; } } Link to comment https://forums.phpfreaks.com/topic/208032-help-comparing-array-diffs-and-inserting-entries/#findComment-1087530 Share on other sites More sharing options...
aa411853 Posted July 17, 2010 Author Share Posted July 17, 2010 Perfect thanks! I was able to take that code, modify the array, and the re-sort based on date and works perfectly. May not be pretty, but it works!! Link to comment https://forums.phpfreaks.com/topic/208032-help-comparing-array-diffs-and-inserting-entries/#findComment-1087550 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.