'Transpose csv file data [duplicate]
I need help to assign keys
to an array
in PHP.
My code is:
//First I make an array of a csv file
$file="C:\path-to-csv\file.csv";
$csv= file_get_contents($file);
$array = array_map("str_getcsv", explode("\n", $csv));
The array
:
//echo json_encode($array);
["0","20150717","2:57:00","1437145020","1.56084","1.56096","1.56084","1.56094","5"],
["1","20150717","2:56:00","1437144960","1.56071","1.56089","1.56071","1.56089","9"],
["2","20150717","2:55:00","1437144900","1.5607","1.5607","1.56064","1.56064","2"], //continue
From the result of $array
, I need to assign a specific key
to a specific column and create a new array
"$newArray
". So, the result looks like this:
//$newArray should print:
"ID" : [0, 1, 2], //I would like delete this value
"n" : [20150717, 20150717, 20150717], //I would like delete this value
"d" : [2:57:00, 2:56:00, 2:55:00], //I would like delete this value
"t" : [1437145020, 1437144960, 1437144900], //column 4
"o" : [1.56084, 1.56071, 1.5607], //column 5
"h" : [1.56096, 1.56089, 1.5607], // column 6
"l" : [1.56084, 1.56071, 1.56064], // column 7
"c" : [1.56094, 1.56089, 1.56064], //column 8
"v" : [5, 9, 2] //column 9
I have tried to do it through loops and some functions such as array_fill_keys
and array_column
but I can not get the desired result. I would greatly appreciate if you can help me, the $array
has more than 1000 entries so it would be really important to optimize the code execution speed, and honestly exceeds my knowledge and I have not seen anything in Google to help me accomplish this.
Thanks for your time, sorry for my grammar.
Solution 1:[1]
If you're using PHP 5.5, you can make use of array_column
:
$newArray = array(
't' => array_column($array, 3),
'o' => array_column($array, 4),
'h' => array_column($array, 5),
...
);
If you're using an older PHP, you can find a PHP implementation of it at Is there a function to extract a 'column' from an array in PHP?
Solution 2:[2]
EDIT Pretty much, this solution can be used <5.5, when array_column is not available to you.
More than 1000 entries does not seem to be that much for a foreach loop.
$keys = array('t','o','h','l','c','v');
$newArray = array();
foreach ($array as $j) {
$r = array_slice($j, 3);
foreach ($r as $i => $v) $newArray[$keys[$i]][] = $v*1;
}
Json encoded result will be
"t":[1437144900,1437144900,1437145020],
"o":[1.5607,1.5607,1.56084],
"h":[1.5607,1.5607,1.56096],
"l":[1.56064,1.56064,1.56084],
"c":[1.56064,1.56064,1.56094],
"v":[2,2,5]
Running an array containing 10.000 entries took
0.020426
You can test yourself on PhpFiddle.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | mickmackusa |
Solution 2 |