Skip to content
Advertisement

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

I have this kind of array:

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%

I need to obtain this:

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%

Can anyone help me please?

Advertisement

Answer

Use str_getcsv, as it CSV, then just assign the first and second columns as the array keys, normalising it and then once you have that you can loop over it and built your desired result.

So aiming to make this structure:

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%
        )

)

You can loop over to make:

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%; 

Like:

<?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

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement