janjua Posted November 16, 2013 Share Posted November 16, 2013 Hi this is my first post after registering here. Please help me. I have a string of user data comma separated as below and pipe separated.I have been trying to remove duplicates by converting it to array. And even with php But it all does not works. My data looks like below: Marja_Roxburgh|abc@abc.com|123-456-7890|N/A|2011-11-17|N/A|N/A|N/A|N/A|N/A|120, Santa_Roxburgh|bmw@abc.com|123-456-7890|N/A|2013-11-17|N/A|N/A|N/A|N/A|N/A|10, Marja_Roxburgh|abc@abc.com|123-456-7890|N/A|201-11-17|N/A|N/A|N/A|N/A|N/A|300, Saga_Shera|xyz@abc.com|123-456-7890|N/A|2013-11-17|N/A|N/A|N/A|N/A|N/A|0, Marja_Roxburgh|abc@abc.com|123-456-7890|N/A|2013-11-17|N/A|N/A|N/A|N/A|N/A|120 I have tried What's the best way to remove duplicates from a string in PHP (or any language)?, detecting duplicate string in a explode function php and like this How to detect duplicate values in PHP array? one too. But none of these works in my case. Coz my data is not unique for same User say Marja_Roxburgh. I wants to remove all entries of Marja_Roxburgh based on its email but also wants to keep the first one only and sum all amounts from its transactions. I've been googling for any logic Im not able to understand what to do this it. How Do I keep only first Record of Marja_Roxburgh and remove all other of her. And also sum all her Amounts before removing her data? I'm missing the logic to understand and solve this problem. Can somebody help me understand this logic? any Ideas? Thanks Quote Link to comment https://forums.phpfreaks.com/topic/283979-remove-all-instances-of-a-string-but-keep-only-one-in-php-also-sum-amounts/ Share on other sites More sharing options...
Barand Posted November 16, 2013 Share Posted November 16, 2013 try $data = "Marja_Roxburgh|abc@abc.com|123-456-7890|N/A|2011-11-17|N/A|N/A|N/A|N/A|N/A|120, Santa_Roxburgh|bmw@abc.com|123-456-7890|N/A|2013-11-17|N/A|N/A|N/A|N/A|N/A|10, Marja_Roxburgh|abc@abc.com|123-456-7890|N/A|2012-11-17|N/A|N/A|N/A|N/A|N/A|300, Saga_Shera|xyz@abc.com|123-456-7890|N/A|2013-11-17|N/A|N/A|N/A|N/A|N/A|0, Marja_Roxburgh|abc@abc.com|123-456-7890|N/A|2013-11-17|N/A|N/A|N/A|N/A|N/A|120"; $array = array_map('trim', explode(',', $data)); $results = array(); foreach ($array as $record) { $recArray = explode('|', $record); $key = $recArray[0]; $qty = $recArray[10]; if (isset($results[$key])) $results[$key] += $qty; else $results[$key] = $qty; } echo '<pre>',print_r($results, true),'</pre>'; /**** RESULTS ******************** Array ( [Marja_Roxburgh] => 540 [Santa_Roxburgh] => 10 [Saga_Shera] => 0 ) **********************************/ Quote Link to comment https://forums.phpfreaks.com/topic/283979-remove-all-instances-of-a-string-but-keep-only-one-in-php-also-sum-amounts/#findComment-1458627 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.