4

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[]);
}
1
  • What are the conditions that you consider to be 'similar'? Commented Oct 2, 2012 at 23:37

1 Answer 1

2

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)
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks this answer has really helped me, I appreciate your time and effort here.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.