首页 > 解决方案 > 来自 .csv 的组数组 | PHP

问题描述

我有这段代码,我想做的是,将来自 .csv 的数据按 Player 分组,然后按年份和联赛分组,例如,我将有 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 => kills [1,2,3] ;2020 => 杀死 [6,9,12]

我怎样才能做到这一点?

那是.csv

gameid,数据完整性,网址,联赛,年份,拆分,季后赛,日期,游戏,补丁,playerid,边,位置,球员,球队,冠军.....

那是我的代码;

<?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>';
}

?>

在此处输入图像描述

标签: phparraysmultidimensional-array

解决方案


您正在添加到$kills数组中,而不考虑年份。因此,当您解析 year2021时,$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;
    }
}

查看工作演示


推荐阅读