php - 来自 .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>';
}
?>
解决方案
您正在添加到$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;
}
}
查看工作演示。
推荐阅读
- sql-server-2017 - 安装 SQL Server 2017 Developer Edition 时的部分用户名
- javascript - 暂停并重新启动我的自定义 Vue 滑块
- sparql - 在 RDF 中表示事务/时间
- angular - 角材料版本 5 -
不支持? - vue.js - 如何使用 Vue.js 重置单击 Beufy 表时发生的排序事件
- php - 将所有列从一个表复制到另一个表但需要指定几列 php 变量
- python - 每个 epoch 后的 TensorFlow tf.data 处理开发集
- laravel-5.7 - 从数据库中提取单引号并使用 Laravel 在页面上显示
- php - 子对象无法访问父对象的受保护属性
- javascript - 在 Javascript 中定义数组不能按预期工作