Jump to content

Remove duplicate array by keyword


darkminos

Recommended Posts

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.

Link to comment
https://forums.phpfreaks.com/topic/266035-remove-duplicate-array-by-keyword/
Share on other sites

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;
}

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.