首页 > 解决方案 > Array_sum 似乎无法正常工作 PHP

问题描述

我正在玩英雄联盟 $api 和异步请求,但现在我遇到了一个问题,我无法汇总参与者 id == 1 的所有击杀数

array_sum 仅显示每场比赛的击杀数,而不是所有(屏幕截图)的总和,预期结果为 122(参与者 ID 1 的所有击杀数总和)

这是我的代码:

<?php



// Function to be called on request success
 $onSuccess = function (Objects\MatchDto  $match) {

  foreach ($match->participants as $team) {
       
        if ($team->participantId==1 and $team->teamId==100) {
            
              $t[]=$team->stats->kills.'</br>';
              var_dump (array_sum($t)); echo '</br>';

        }    
    } 


};
// Function to be called on request failure
$onFailure = function ($ex) {
    echo "Error occured: {$ex->getMessage()}";
};

 //I have a bunch of match_ids from league of legends games saved in my db
 // so,  foreach $custom is to get all match_ids
 // $api variable is an array with all initializtion settings
 // $match is basically getting me the match with that matchid from my db ex: getMatch('1234567')

    foreach ($custom as $games) {
    
    $api->nextAsync($onSuccess, $onFailure);

    $match=$api->getMatch($games->match_id);
    
}



$api->commitAsync();



?>

在此处输入图像描述

这是 array_sum 返回给我的,而不是预期的结果 122。

标签: phparrayslaravelasynchronous

解决方案


<?php

    $onSuccess = function(Objects\MatchDto  $match, &$t){
        foreach ($match->participants as $team){
            if ($team->participantId==1 and $team->teamId==100){
                  $t+=$team->stats->kills;
            }    
        }
    };

    $onFailure = function($ex){
        echo "Error occurred: {$ex->getMessage()}";
    };
    $t = 0;
    foreach($custom as $games){
        $api->nextAsync($onSuccess, $onFailure);
        $match=$api->getMatch($games->match_id);
    }
    $api->commitAsync();
    echo $t."<br>";

?>    

让我知道这对你有什么影响。我之前没有注意到你也在循环多个匹配项(多次调用 onSuccess)。


推荐阅读