两个数组上的php similar_text函数

时间:2012-10-02 23:33:11

标签: php arrays if-statement foreach

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

$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循环正确引用数组,并使用 if 语句与similar_text函数一起指定两者之间所需的相似百分比火柴。

例如(在foreach循环中):

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

1 个答案:

答案 0 :(得分: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)