簡體   English   中英

組數組來自.csv | PHP

[英]Group Array from .csv | PHP

我有這段代碼,我想做的是,將來自.csv 的數據按玩家分組,然后按年份和聯賽分組,例如,我將有 faker -> 2021 -> lck->data ; ->2020->lck->數據

有時當一個球員一年打過一個以上聯賽時,faker->2021->lck->data | 2021->kespa->數據

問題是當我顯示擊殺數時(圖片),2020 年將添加 2021 年的擊殺數和 2020 年的擊殺數。我想要的是 2020 年顯示該聯盟和那一年的擊殺數,與 2021 年相同。

結果我得到:

Faker => 2021 => 殺死 [1,2,3]; 2020 => 殺死 [1,2,3,6,9,12];

預期結果是:
Faker => 2021 => 殺死 [1,2,3]; 2020 => 殺死 [6,9,12]

我怎樣才能做到這一點?

那就是 csv

游戲ID,數據完整性,url,聯賽,年份,拆分,季后賽,日期,游戲,補丁,playerid,側面,position,球員,團隊,冠軍.....

那是我的代碼;

<?php
  
$csvFileData = file('./datalck.csv');
$dataMatch = [];

foreach ($csvFileData as $lines) {
    $data[] = str_getcsv($lines);
}
  

foreach ($dataMatch as $matchs) {
  // So here i'm grouping the array by player
 //[3] is the position for the league
 //[4] is the position for year
 //[13] is the position of player name ,
 //[23] The position of kills
    if ($matchs[13] != NULL and $matchs[13] != "") {

        $group[$matchs[13]][] = [
            'Player' => $matchs[13],
            "kills" => $matchs[23],
            'league' => $matchs[3],
            'year' => $matchs[4],


        ];
    }
}


foreach ($group as $players => $p) {


    $kills = [];       
    foreach ($p as $op) {

        $kills[] = $op['kills'];

        $group2[$op['Player']][$op['year']][$op['league']] = [
            "Player" => $op['Player'],
            "kills" => $kills,
            "league" => $op['league'],
            "year" => $op['year'],
        ];
    }
}

foreach ($group2 as $op2) {

    echo '<pre>';
    var_dump(($group2));
    echo '</pre>';
}

?>

在此處輸入圖像描述

您正在添加到$kills數組,而不考慮年份。 因此,當您解析2021時, $kills數組已經包含2020的數據。

您可以第一次(每年)創建一個空數組,然后填充它。

foreach ($group as $players => $p)
{
    foreach ($p as $op)
    {
        // variables for readability
        $plyr = $op['Player'];
        $year = $op['year'];
        $leag = $op['league'];
        $kills = $op['kills'];

        // create the initial state
        if (!isset($group2[$plyr][$year][$leag])) 
        {
            $group2[$plyr][$year][$leag] = [
                "Player" => $plyr,
                "league" => $leag,
                "year" => $year,
                "kills" => [], // empty array
            ];
        }

        // add value to array for the player/year/league :
        $group2[$plyr][$year][$leag]['kills'][] = $kills;
    }
}

查看工作演示

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM