darkminos Posted July 21, 2012 Share Posted July 21, 2012 Hi, another simple one which I can't work out: I have a function to remove duplicates from an array, however I need to modify it to remove duplicates by 'title' if ( !function_exists( "arrayUnique" ) ){ function arrayUnique ( $rArray ){ $rReturn = array (); while ( list( $key, $val ) = each ( $rArray ) ){ if ( !in_array( $val, $rArray ) ) array_push( $rReturn, $val ); } return $rReturn; } } Array format: Array ( [0] => Array ( [pic] => 1.jpg [link] => http:// [from] => shop [title] => title1 [cost] => 0.01 [description1] => asd [description2] => fgh [description3] => jkl [category] => LED ) [1] => Array ( [pic] => 1.jpg [link] => http:// [from] => shop [title] => title [cost] => 0.01 [description1] => asd [description2] => fgh [description3] => jkl [category] => LED ) [2] => Array ( [pic] => 1.jpg [link] => http:// [from] => shop [title] => title1 [cost] => 0.01 [description1] => asd [description2] => fgh [description3] => jkl [category] => LED ) So... what the function needs to do is to look at the titles and remove duplicated entries containing the same title. (if this makes sense) From the array above one of the entries containing '[title] => title1' should be removed leaving the following: Array ( [0] => Array ( [pic] => 1.jpg [link] => http:// [from] => shop [title] => title1 [cost] => 0.01 [description1] => asd [description2] => fgh [description3] => jkl [category] => LED ) [1] => Array ( [pic] => 1.jpg [link] => http:// [from] => shop [title] => title [cost] => 0.01 [description1] => asd [description2] => fgh [description3] => jkl [category] => LED ) Order is irrelevant. Quote Link to comment https://forums.phpfreaks.com/topic/266035-remove-duplicate-array-by-keyword/ Share on other sites More sharing options...
Barand Posted July 21, 2012 Share Posted July 21, 2012 try function arrayUnique ($arr) { foreach ($arr as $k=>$v) { foreach ($arr as $k2=>$v2) { if ($k2 <= $k) continue; if ($v2['title'] == $v['title']) { unset($arr[$k2]); } } } return $arr; } Quote Link to comment https://forums.phpfreaks.com/topic/266035-remove-duplicate-array-by-keyword/#findComment-1363237 Share on other sites More sharing options...
darkminos Posted July 21, 2012 Author Share Posted July 21, 2012 Very interesting, I had almost exactly the same function before and changed it as it was messing up my array_multisort(), now I know it was due to lack of re-indexing after the duplicates are removed. Thanks for that Quote Link to comment https://forums.phpfreaks.com/topic/266035-remove-duplicate-array-by-keyword/#findComment-1363309 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.