使用PHP计算数组中的值总和

时间:2019-05-30 07:15:11

标签: php arrays

我正在尝试为我的计划合并员工的分数。我的样本是一位员工的评价超过一位。因此,基本上来说,如果员工1的得分分别为87和90,则总数应为177。计算后,我需要返回得分最高的结果。 到目前为止,这里是我的示例代码(我简化了该问题的代码,因为发布原始代码太长了):

$scores = array( 
    array(1, "allan", 90),
    array(2, "allan", 85),
    array(3, "mark", 100),
    array(4, "jason", 88),
    array(5, "allan", 92),
    array(6, "mark", 77),
    array(7, "mark", 88),
    array(8, "jason", 90)
); 

print_r($scores);

get_topemployee($scores); 

function get_topemployee($scores) {
    $total_score = 0;
    $combined_score = array();

    foreach($scores as $key) {
        for($i=0; count($scores) <= $i; $i++) {
            if($key[0] == $key[0][$i]) {
                $total_score += $key[1];
            }
            $combined_score[] = array($key[0], $key[1], $total_score);
        }
    }

    $employee = ""; // employee with highest score
    $compare_score = 0;
    foreach($combined_score as $value) {
        $compare_score = $value[1];
        if($value[1] >= $compare_score) {
            $employee = $value[0];
        }
    }

    return $employee;
}

结果不会返回得分最高的员工,并且不确定我的代码中哪个不正确。谢谢你的帮助

执行以下操作:-https://3v4l.org/WhVaN

5 个答案:

答案 0 :(得分:3)

您可以使用Series.str.extract将分数数组转换为由员工编制索引的总分数数组:

    message.author.send({
        embed: {
            color: 37119,
            title: "**What do you want to order?**",
            description: "1️⃣ Design \n 2️⃣ Bot \n 3️⃣ Domainname \n 4️⃣ Bothosting \n 5️⃣ Minecrafthosting",
            timestamp: new Date()
        }
    });
    const collector = new Discord.MessageCollector(message.channel.type == "dm", m => m.author.id === message.author.id, {
        time: 10000
    });
    collector.on('collect', message => {
        const type = message.content;
        const messageauthor = message.author


        if (message.content == "design" || message.content == "Design" || message.content == "1") {
            console.log("log1")
        }
        else if (message.content == "bot" || message.content == "Bot" || message.content == "2") {
            console.log("log2")
        }
        else if (message.content == "domainname" || message.content == "Domainname" || message.content == "3") {
            console.log("log3")
        }
        else if (message.content == "bothosting" || message.content == "Bothosting" || message.content == "4") {
            console.log("log4")
        }
        else if (message.content == "minecrafthosting" || message.content == "Minecrafthosting" || message.content == "5") {
            console.log("log5")






        } else {
            message.channel.send("Choose between 1-5");
        }
    })
}```

UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'setTimeout' of undefined

然后您可以使用array_reduce对数组进行反向排序,同时保持键关联。然后,您可以使用arsort获取第一个元素的密钥,这将是得分最高的员工的名字:

$scores = array_reduce($scores, function ($c, $v) { 
    $name = $v[1];
    if (isset($c[$name])) {
        $c[$name] += $v[2];
    }
    else {
        $c[$name] = $v[2];
    }
    return $c;
}, array());

输出:

arsort($scores);
echo key($scores);

key

要打印所有分数,只需allan

print_r($scores)

或者只打印最高分数,将Array ( [allan] => 267 [mark] => 265 [jason] => 178 ) 更改为echo key($scores);

echo key($scores) . ' ' . current($scores);

Demo on 3v4l.org

答案 1 :(得分:3)

您可以通过简单的foreach循环来做到这一点:

foreach($scores as $e) {
    if (!isset($res[$e[1]])) $res[$e[1]] = 0;
    $res[$e[1]] += $e[2]; 
}
print_r(array_keys($res, max($res)));

实时示例:3v4l

答案 2 :(得分:3)

这是您的摘录,请参阅内联文档以获取说明

$result = [];
array_walk($scores, function($item) use(&$result){
   // pushing on the behalf of name and checking if not isset with '??'
   $result[$item[1]] = ($result[$item[1]] ?? 0) + $item[2]; 
});
// searching for index with max value in result and show max value too 
echo array_search(max($result), $result).' -> '. max($result);

array_search —在数组中搜索给定值,如果成功,则返回第一个对应的键。
array_walk —将用户提供的函数应用于数组的每个成员

输出

allan -> 267

Demo Link

答案 3 :(得分:1)

$scores = [
    [1, 'allan', 90],
    [2, 'allan', 85],
    [3, 'mark', 100],
    [4, 'jason', 88],
    [5, 'allan', 92],
    [6, 'mark', 77],
    [7, 'mark', 88],
    [8, 'jason', 90]
];

function maxScore(array $scores): string {
    $preparedScores = [];

    foreach ($scores as $score) {
        $key   = $score[1];
        $value = $score[2];

        if (isset($preparedScores[$key])) {
            $preparedScores[$key] += $value;
        } else {
            $preparedScores[$key] = $value;
        }
    }

    arsort($preparedScores);

    return array_key_first($preparedScores);
}

echo maxScore($scores);

结果:

allan

答案 4 :(得分:0)

$scores = array( 
    array(1, "allan", 90),
    array(2, "allan", 85),
    array(3, "mark", 100),
    array(4, "jason", 88),
    array(5, "allan", 92),
    array(6, "mark", 77),
    array(7, "mark", 88),
    array(8, "jason", 90)
); 


get_topemployee($scores); 

function get_topemployee($scores) {
    $total_score = 0;
    $combined_score = array();

    $highest_score = 0;
    $highest_employee = '';

    foreach($scores as $key => $value) {
        if ( ! isset($combined_score[$value[1]])) {
            $combined_score[$value[1]] = $value[2];
        }
        else {
            $combined_score[$value[1]] += $value[2];
        }

        if ($highest_score < $combined_score[$value[1]]) {
            $highest_score = $combined_score[$value[1]];
            $highest_employee = $value[1];  //the highest value employee
        }   
    }

    return $highest_employee;
}