Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
86 views
in Technique[技术] by (71.8m points)

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?

question from:https://stackoverflow.com/questions/65601203/how-can-i-achieve-a-new-array-with-columns-from-another-arrays-rows-php

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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, "
") 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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...