如何使用另一个数组的行中的列创建一个新数组? [php]

How can I achieve a new array with columns from another array's rows? [php]

我有这样的数组:

2020-01; Starter1; 11,4%
2020-01; Starter2; 6,9%
2020-01; Starter3; 9,5%
2020-01; Starter4; 11,1%
2020-02; Starter1; 5,8%
2020-02; Starter2; 5,8%
2020-02; Starter3; 10,0%
2020-02; Starter4; 6,4%

我需要得到这个:

Year;    Starter1; Starter2; Starter3; Starter4
2020-01; 11,4%;     6,9%;     9,5%;     11,1%
2020-02; 5,8%;     10,0%;     10,0%;    6,4%

有人能帮帮我吗?

使用 str_getcsv,因为它是 CSV,然后只需将第一列和第二列指定为数组键,对其进行规范化,然后一旦你拥有它,你就可以遍历它并构建你想要的结果。

所以打算做这个结构:

Array
(
    [2020-01] => Array
        (
            [Starter1] => 11,4%
            [Starter2] => 6,9%
            [Starter3] => 9,5%
            [Starter4] => 11,1%
        )

    [2020-02] => Array
        (
            [Starter1] => 5,8%
            [Starter2] => 5,8%
            [Starter3] => 10,0%
            [Starter4] => 6,4%
        )

)

你可以循环制作:

Year;    Starter1; Starter2; Starter3; Starter4
2020-01; 11,4%;    6,9%;     9,5%;     11,1%;    
2020-02; 5,8%;     5,8%;     10,0%;    6,4%; 

喜欢:

<?php
$str = '2020-01; Starter1; 11,4%
2020-01; Starter2; 6,9%
2020-01; Starter3; 9,5%
2020-01; Starter4; 11,1%
2020-02; Starter1; 5,8%
2020-02; Starter2; 5,8%
2020-02; Starter3; 10,0%
2020-02; Starter4; 6,4%';

// normalise and group data
$result = [];
foreach(str_getcsv($str, "\n") as $row){
    $row = array_map('trim', str_getcsv($row, ";"));
    $result[$row[0]][$row[1]] = $row[2];
}

// loop over to specification
echo 'Year;    Starter1; Starter2; Starter3; Starter4'.PHP_EOL;
foreach ($result as $year => $row) {
    echo $year.'; ';
    foreach ($row as $key => $col)
        echo $col.";".str_repeat(' ', (($v = strlen($key)-(strlen($col)-1)) && $v > 0) ? $v : 0);
    echo PHP_EOL;
}

https://3v4l.org/11VaW