如何从数据库中获取类似文本?

时间:2012-12-17 05:04:45

标签: php database

我有像这样的代码=

<?php
  $sql=mysql_query("select first_name, middle_name, last_name, address, mothers_name from tabel");
  while($s=mysql_fetch_array($sql))
  {
      $firstname=$s['first_name'];
      $middlename=$s['middle_name'];
      $lastname=$s['last_name'];    
      $name_all= "$firstname"."&nbsp;$middlename"."&nbsp;$lastname";
      similar_text($name_all, $name_all, $percent); 
      echo "Presentasi = $percent %";
  } 
?>

但每个名字的结果都是100%

example:
1 Adi Surya 100%
2 Budi Surya 100%
3 Surya Adi 100%

我想要这样的结果=

1 Adi Surya 63%
1 Surya Adi 63%
2 Budi Surya 

请帮帮我怎么办?

4 个答案:

答案 0 :(得分:3)

试试这个:

<?php
$sql=mysql_query("select first_name, middle_name, last_name, address, mothers_name from tabel");
 while($s=mysql_fetch_array($sql))
  {
      $firstname=$s['first_name'];
      $middlename=$s['middle_name'];
      $lastname=$s['last_name'];    
      $name_all[]= "$firstname"."&nbsp;$middlename"."&nbsp;$lastname";
  }
for($i=0;$i<=count($name_all)-1;$i++){
  for($j=$i+1;$j<=count($name_all)-1;$j++){
    $result[]=checkforsimilarity($name_all[$i],$name_all[$j]);
  }
}
echo "<pre>";
die(print_r($result));

function checkforsimilarity($a,$b){
    if($a!=$b){
        similar_text($a,$b,$percent);
        return "<br />percentage of similarity between $a and $b is $percent <br />";
    }
}
?>

答案 1 :(得分:2)

您正在此功能中将$name_all与自身进行比较:

similar_text($name_all, $name_all, $percent);

当然,比较是100%,因为$ name_all等于它自己。

答案 2 :(得分:2)

为什么不尝试在MySQL查询中执行此操作?

我没有测试过,但我认为这会有所帮助:

SELECT 
    User.*,
    COUNT(*) AS Total,
    (COUNT(*) / (SELECT COUNT(*) FROM User WHERE first_name='Popular')) * 100 AS 'Percentage', 
FROM 
    User
WHERE last_name='Popular'
GROUP BY User.first_name;

我相信这会有效,但您可能需要根据需要进行编辑。

答案 3 :(得分:1)

Getting percentage using php code.Try this
 <?php
      $sql=mysql_query("select first_name, middle_name, last_name, address, mothers_name from tabel");
    $cnt=0;
     while($s=mysql_fetch_array($sql))
      {
          $firstname=$s['first_name'];
          $middlename=$s['middle_name'];
          $lastname=$s['last_name'];    
          $name_all= "$firstname"."&nbsp;$middlename"."&nbsp;$lastname";
          if(isset($arr[$name_all])){
            $arr[$name_all] = $arr[$name_all]+1;
          }else{
            $arr[$name_all] = 1;
          }
          $cnt++;
      }
      echo $cnt;
      foreach($arr as $key=>$val){
        echo $key."  percent=". ROUND(($val/$cnt)*100,2)."</br>";
      }
    ?>