2011-03-29 41 views
0


如何找到百分比,并将其保存到mysql

$ar1=array("Mobile","shop","software","hardware"); 
$arr2=arry("shop","Mobile","shop","software","shop")
我想比较ARR2的元素ARR1即

 
    $counts=array(); 
    foreach($arr2 as $val) 
    { 
     if(in_array($val, $arr1)) 
     {  
      array_push($counts,$val); 
      // here will my insert query to insert data in mysql table. 
     } 
    } //end of foreach loop 
    $specific_fields = array_count_values($counts); /* Array ([shop] => 3 [software] => 1 [Mobile] => 1) 
     $total_fields=count($arr2); // output will be 5 

Now here first i want to find percentage for each element 
i.e $per1=$specific_fields['shop']/$total_fields; 
     $per2=$per1*100; 
     $percentage=number_format($per2,0); 

when i find the percentage how can i update below query with the percentage values of all elements. 

    $query="update table_name set shop='$percentage_value',Mobile='$percentage_value'......."; 
    } 


是否有自动更新所有的字段以动态的方式。

+1

一般来说,将更改的派生值保存到关系数据库并不是一个好习惯。保存传入的原始值并在需要时使用查询来计算派生值会更加有效。这有两个优点 - 没有更新,只有INSERT;以及在许多不同类型的计算中使用原始数据的能力。 值得保存更改派生值的次数之一是汇总表,它可以作为高价查询结果的缓存。 – dnagirl 2011-03-29 12:56:06

回答

0
+0

你的意思是在查询中计算它吗?如果是这样,看看我的其他答案。 – user578368 2011-03-29 12:50:24

+0

我不想计算在查询中。首先,我想计算每个元素的百分比,即“商店,移动,软件”,然后相应地更新查询。 – hunter 2011-03-29 12:54:53