我需要帮助才能将keys
分配给PHP中的array
。
我的代码是:
//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));
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
从$array
的结果中,我需要为特定列分配特定的key
并创建新的array
“$newArray
”。所以,结果如下:
//$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
我试图通过循环和一些函数(例如array_fill_keys
和array_column
来完成它,但我无法获得所需的结果。如果您能帮助我,我将非常感谢$array
有超过1000个条目,因此优化代码执行速度非常重要,老实说超出我的知识,我没有在Google上看到任何帮助我的东西完成这个。
谢谢你的时间,对不起我的语法。
答案 0 :(得分:0)
编辑很多时候,当您无法使用array_column时,此解决方案可以使用< 5.5。
对于foreach循环,超过1000个条目似乎没那么多。
$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编码结果将是
"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]
运行包含10.000个条目的数组
0.020426
您可以在PhpFiddle上自行测试。
答案 1 :(得分:0)
如果您使用的是PHP 5.5,则可以使用array_column
:
$newArray = array(
't' => array_column($array, 3),
'o' => array_column($array, 4),
'h' => array_column($array, 4),
...
);
如果你使用的是较旧的PHP,你可以在Is there a function to extract a 'column' from an array in PHP?找到它的PHP实现