Reputation: 145
I have two large arrays of scraped product names and prices similar to the following:
$one=array('grape'=>'0.40','apple'=>'1.20','banana'=>'1.80','lemon'=>'10.43');
$two=array('grappe'=>'1.20','kiwi'=>'7.54','banaana'=>'3.20','aubergine'=>'2.32');
I am attempting to iterate over the arrays using the similar_text function to return the keys that match eachother closely. For example i would like to extract the values of 'grappe'=>'1.20'
and 'banaana'=>'3.20'
from the above example.
I am unsure how to reference the arrays and pass them to the similar_text function as this function only accepts string data. I presume i will need to correctly reference the arrays using a foreach
loop and use an if statement in conjunction with the similar_text
function to specify the desired percentage of similarity between the two matches.
For example (within the foreach loop):
if ($result[] = (similar_text( $one, $two)) > 80) {
var_dump($result[]);
}
Upvotes: 4
Views: 3480
Reputation: 95161
similar_text( $one, $two)
Returns the number of matching chars in both strings so To get percentage you should run similar_text($one, $two, $percent);
insted
Example
$one = array('grape' => '0.40','apple' => '1.20','banana' => '1.80','lemon' => '10.43');
$two = array('grappe' => '1.20','kiwi' => '7.54','banaana' => '3.20','aubergine' => '2.32');
$result = array();
foreach ( $one as $key => $value ) {
foreach ( $two as $twoKey => $twoValue ) {
similar_text($key, $twoKey, $percent);
if ($percent > 80) {
$result[$key] = array($value,$twoValue);
}
}
}
var_dump($result);
Output
array
'grape' =>
array
0 => string '0.40' (length=4)
1 => string '1.20' (length=4)
'banana' =>
array
0 => string '1.80' (length=4)
1 => string '3.20' (length=4)
Upvotes: 2