所以我试图在我们的数据库中找到最佳模型,以匹配用户输入的高度,重量等值。我根据加权值生成了一个名为heightMatchMultiple的变量,并将所有结果存储在全局数组$ models中。如何将数学仅应用于____MatchMultiple字段,然后按结果排序?例如,我存储每个模型的modelID,但我只想添加其他值,然后找到最高的平均值。
以下是一些相关代码:
while($row=mysqli_fetch_array($array))
{
$userHeight=$_POST['height'];
$userWeight=$_POST['weight'];
$userShoulder=$_POST['shoulder'];
$userWaist=$_POST['waist'];
$userInseam=$_POST['inseam'];
$heightMatchMultiple=0;
//creates a weighted variable for height
if(isset($row['modelHeight']))
{
if($userHeight==$row['modelHeight'])
{
$heightMatchMultiple=10;
}
elseif($userHeight==($row['modelHeight']+1) || $userHeight==($row['modelHeight']-1))
{
$heightMatchMultiple=9;
}
//same code down til multiple hits 1
else
{
$heightMatchMultiple=1;
}
//similar code for the weight, shoulders, etc.......
//....
array_push($models,array("modelID" => $row['modelID'],
"modelHeightMatch" => $heightMatchMultiple,
"modelWeightMatch" => $weightMatchMultiple,
"modelShoulderMatch" => $shoulderMatchMultiple,
"modelWaistMatch" => $waistMatchMultiple,
"modelInseamMatch" => $inseamMatchMultiple));
我想创建一个函数,在数组中添加所有_____MatchMultiple变量(不包括modelID),然后除以每个变量中数组中的项目数。通过这种方式,我可以找出最接近匹配的模型。
答案 0 :(得分:0)
这个sum_array()函数能为你解决吗?
function safe_key_inc(&$arr, $key, $inc)
{
if (array_key_exists($key, $arr))
$arr[$key] += $inc;
else
$arr[$key] = $inc;
}
function sum_array($arr)
{
$sum_arr = [];
foreach ($arr as $el)
foreach ($el as $key => $val)
{
if (strstr($key, "Match"))
safe_key_inc($sum_arr,$key,$val);
}
return $sum_arr;
}
答案 1 :(得分:0)
function getAverage($array) {
var $myTotal = 0
for ($i = 1; $i<= sizeof($array) - 1; $i++) {
$myTotal += $array[$i]
}
var $myAverage = $myTotal/(sizeof(array) - 1)
return($myAverage)
}