doufenpaiyu63706
2015-11-24 20:54
浏览 24
已采纳

如何将数组的某些值一起添加,然后按总和进行排序?

So I am trying to find the best model within our database to match the user's inputted values for Height, Weight, etc. I have generated a variable called heightMatchMultiple based on weighted values and stored all the results in a global array $models. How can I apply math to only the ____MatchMultiple fields and then sort by the result? For example, I store the modelID of each model but I only want to add up the other values and then find the highest average.

Here is some relevant code:

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));

I would like to make a function that adds all of the _____MatchMultiple variables within the array (not including modelID) and then divides by the number of items within the array for each. This way I can find out which model is the closest match.

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • doutuo1908 2015-11-24 21:10
    已采纳
    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)
    }
    
    点赞 打赏 评论
  • dongxia2068 2015-11-24 21:06

    Does this sum_array() function solve it for you?

    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;
    }
    
    点赞 打赏 评论

相关推荐 更多相似问题