bpops Posted May 27, 2008 Share Posted May 27, 2008 I have a bit of a complicated problem. I have a multidimensional array such as this: $arr[0]['x'] = 'one'; $arr[0]['y'] = 'two'; $arr[0]['z'] = 'three'; $arr[1]['x'] = 'six'; ... Now, I want to take all of the $arr[..]['y'] elements that are equal and group them. I think I could use array_unique(), however I will lose the information of how many were the same. What I want to do is have one more element $arr[0]['num'] = 1; To tell me how many were with that value of 'y' to begin with. So far the only way I've come up to do this is to go through the entire array and for every element, go back to every previous element and check for a duplicate. If it is, add one to the 'num', and delete the current record. But this will be a very slow process. Hope that's not too confusing. Any ideas? Link to comment https://forums.phpfreaks.com/topic/107381-removing-duplicates-but-knowing-how-many-removed/ Share on other sites More sharing options...
haku Posted May 27, 2008 Share Posted May 27, 2008 You could use count() on the array before you remove the elements, then use count() again after you combine the elments and subtract the difference. Link to comment https://forums.phpfreaks.com/topic/107381-removing-duplicates-but-knowing-how-many-removed/#findComment-550533 Share on other sites More sharing options...
bpops Posted May 27, 2008 Author Share Posted May 27, 2008 haku, that would only work if there was only one value which was duplicated. But I want to know how many of each value is duplicated. Currently I'm working on using array_count_values() on a separate array that references the array of key's i'm interested in. I think it will end up working, it's just messy. Link to comment https://forums.phpfreaks.com/topic/107381-removing-duplicates-but-knowing-how-many-removed/#findComment-550537 Share on other sites More sharing options...
bpops Posted May 27, 2008 Author Share Posted May 27, 2008 Ok, I've come up with a solution. It's a bit messy, and I have just one problem left. array_unique() will consolidate NULLS. For example, $a[] = 'one'; $a[] = ''; $a[] = 'two'; $a[] = 'two'; $a[] = ''; will result in [0] => 'one', [1] => '', [2] => 'two' when I actually want [0] => 'one', [1] => '', [2] => 'two', [3] => ''; Anyone have an idea on how to correct for this? Link to comment https://forums.phpfreaks.com/topic/107381-removing-duplicates-but-knowing-how-many-removed/#findComment-550560 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.