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

问题描述 投票:0回答:3

$ar1=array("Mobile","shop","software","hardware");
$arr2=arry("shop","Mobile","shop","software","shop")
i want to compare the elements of arr2 to arr1 i.e

    $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'.......";
     }

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

php mysql
3个回答

0
投票

使用COUNT函数。例如:update table_name set shop=(COUNT(*) FROM table_name WHERE column meets condition)/(COUNT(*) FROM table_name) * 100, Mobile = ... http://www.tizag.com/mysqlTutorial/mysqlcount.php


0
投票
$specific_fields = array_map(function($val, $total_fields){
  return $val / count($total_fields)
}, $specific_fields, [$arr2]);

print_r($specific_fields);

对于更新的SQL语句应该是这样的

$str_temp = '';
foreach ($specific_fields as $key => $f)
{
  $str_temp .= "$key=$f"
}

$sql = "UPDATE ... SET $str_temp WHERE ID = <ID>"
© www.soinside.com 2019 - 2024. All rights reserved.