I want the $us1 array to be the best matching since it completely matches the $user array.
SO when I put a percentage together they both come back as 100% match. Can someone please help me come up with an idea to make this work. The actual data comes from a mysql database and compares about 10 different arrays to one another and compares them for the best match.
Any and all help is greatly appreciated and thank you in advance.
Seems like a fair enough challenge. I have a solution that may work for you, but I have a quick question first: how would you like it to treat the following two arrays:
Give this a shot and see how it works out for you. I've attempted to comment it the best I can. It returns a float value between 0 and 1, 0 being 0% match, and 1 being 100% match.
PHP Code:
function array_cmp( Array $array_one, Array $array_two ) {
// If both are empty, they are identical! if ( empty( $array_one ) && empty( $array_two ) ) { return 1.; }
// Count the two array values $count_one = count( $array_one ); $count_two = count( $array_two );
// Calculate their intersection $array_int = array_intersect( $array_one, $array_two );
// Count their intersection $count_int = count( $array_int );
// If no intersection, they are nothing alike... if ( 0 === $count_int ) { return 0.; }
// ...but if the intersection count matches both, they are identical! elseif ( $count_int === $count_one && $count_int === $count_two ) { return 1.; }
// Which is larger? We'd like to subtract the smaller from the larger switch ( TRUE ) { // array one was larger case ( $count_one > $count_two ): $count_cmp = $count_one; $difference = ( $count_one - $count_two ); break; // array two was larger case ( $count_two > $count_one ): $count_cmp = $count_two; $difference = ( $count_two - $count_one ); break; // they must then be the same size default: $count_cmp = $count_one; $difference = 0;
}
// Divide the difference by the larger count // - this will always be a float between `0` and `1` // - the further apart the array values, the higher the decimal value // - this is backward, so we correct this by subtracting from 1 // - we then round to the nearest 100th decimal place return round( 1. - floatval( $difference / $count_cmp ), 2 );