The Letter E Posted May 12, 2011 Share Posted May 12, 2011 I have a brain twister in a script i'm working on. It have a multidimensional array that hold values to populate a google charts js script. To make it work as I plan I need to merge the data from similar arrays together. I'll give an example and hopefully it will make more sense. Also, this page is being loaded over ajax so, the faster/smaller the better. Example Array: Array ( [0] => Array ( [item] => 1 [quant] => 2 [price] => 12.5 [day] => 18 [onl] => ) [1] => Array ( [item] => 1 [quant] => 2 [price] => 12.5 [day] => 18 [onl] => ) [2] => Array ( [item] => 1 [quant] => 5 [price] => 12.5 [day] => 17 [onl] => 1 ) [3] => Array ( [item] => 1 [quant] => 12 [price] => 12.5 [day] => 19 [onl] => 1 ) [4] => Array ( [item] => 1 [quant] => 4 [price] => 12.5 [day] => 21 [onl] => ) ) So since array 0 and 1 both have data from sales on the 18th for the same item I would want to merge them into a single array and leave all others in the parent array the same. I apologize in advance if this doesn't make sense, I've been working too many hours. X| If anyone knows of a good solution for this or perhaps a better approach, that would be great. Thank You, E Quote Link to comment https://forums.phpfreaks.com/topic/236164-combine-similar-arrays-additive/ Share on other sites More sharing options...
btherl Posted May 12, 2011 Share Posted May 12, 2011 One approach is to make an associative array with the distinguishing feature as the key (aka a hash table). $lookup_table = array(); foreach ($data as $d) { $key = $d['day'] . "-" . $d['item']; if ($lookup_table[$key]) { # Merge $d into existing data in $lookup_table[$key] } else { $lookup_table[$key] = $d; } } And then you can loop through $lookup_table to get the merged data. Quote Link to comment https://forums.phpfreaks.com/topic/236164-combine-similar-arrays-additive/#findComment-1214276 Share on other sites More sharing options...
The Letter E Posted May 12, 2011 Author Share Posted May 12, 2011 Thank you for the response. At this point I've decided that the best way to combine my data is before it even hits the script using the MySQL SUM(). It handles what the script was going to before it returns the initial rows, which is awesome. Thanks for the reply. I will keep that method in mind. I'm sure it will come in handy in another situation. E Quote Link to comment https://forums.phpfreaks.com/topic/236164-combine-similar-arrays-additive/#findComment-1214619 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.