3

我有两大类刮掉的产品名称和价格,类似于以下内容:

$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');

我正在尝试使用similar_text 函数迭代数组以返回彼此紧密匹配的键。例如,我想从上面的例子中提取'grappe'=>'1.20'和提取值。'banaana'=>'3.20'

我不确定如何引用数组并将它们传递给similar_text 函数,因为该函数只接受字符串数据。我认为我需要使用foreach循环正确引用数组,并结合函数使用ifsimilar_text语句来指定两个匹配项之间所需的相似性百分比。

例如(在 foreach 循环中):

if ($result[] = (similar_text( $one, $two)) > 80) {
    var_dump($result[]);
}
4

1 回答 1

2

similar_text( $one, $two)返回两个字符串中匹配字符的数量,因此要获得百分比,您应该运行similar_text($one, $two, $percent);insted

例子

$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);

输出

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)
于 2012-10-02T23:41:39.010 回答