1

我有一个 CSV 文件,其中有数千个数字。让我们使用这个来简化:

4
7
1
9
3
3
8
6
2

我想要的是输出一个每个键有 3 个数字的数组(用逗号内爆):

array (
  [0] => 4,7,1
  [1] => 9,3,3
  [2] => 8,6,2
)

我已经设法做到这一点,阅读 CSV:

$path = "data.csv";
$row = 1;
if (($handle = fopen($path, "r")) !== FALSE) {
  while (($data = fgetcsv($handle, 1000, "\r\n")) !== FALSE) {
    $cell = 0;
    $table[$row][$cell] = $data[0];
    $cell++;
  }
  fclose($handle);
}

我只是对我必须在哪里增加 $row 和 $cell 以获得我想要的输出感到困惑。你能帮忙吗?

4

4 回答 4

3

使用这个,我测试并工作:

<?php
$path = "data.csv";
$array = explode("\n", file_get_contents("data.csv"));
$numbers = array();
foreach(array_chunk($array, 3) as $number){
    $numbers[] = implode(", ", $number);
}
print_r($numbers);
?>
于 2012-05-02T20:27:14.653 回答
2

一个较小的(即使您已经接受了另一个答案),但并不意味着它“更好”(因为它不是那么容易阅读)。你仍然可以从中学到一些技巧:

$path = "data.csv";
$datas = array_chunk(explode("\n",file_get_contents($path)),3);
array_walk($datas, create_function('&$v,$k', '$v = implode(\', \', $v);'));
var_dump($datas);

比上一个好多了:

$path = "data.csv";  // path to the file
$datas = explode("\n",file_get_contents($path)); 
// $datas contains an array with each csv line as an array row
$finalArray = array(); // empty array we will fill
$datas = array_chunk($datas, 3); // http://fr.php.net/manual/en/function.array-chunk.php
foreach($datas as $data){
    $finalArray[] = implode(', ', $data);
}
var_dump($finalArray);

前一个 :

$path = "data.csv";  // path to the file
$row = 0; // initializing
$datas = explode("\n",file_get_contents($path)); 
// $datas contains an array with each csv line as an array row
$finalArray = array(); // empty array we will fill
// Let's loop $datas \o/
foreach($datas as $index => $data){ // 
    $finalArray[$row] = isset($finalArray[$row]) ? $finalArray[$row].', '.$data : $data; // filling the array
    if(($index+1)%3 == 0) $row++; // We jump from a row to another every 3 lines
}

var_dump($finalArray);
于 2012-05-02T20:15:24.830 回答
1

您必须在循环之外声明单元格,否则它将始终被重置...

这是所需的代码:

$path = "data.csv";
$row = 0;
$cell = 0;
if (($handle = fopen($path, "r")) !== FALSE) {
  while (($data = fgetcsv($handle, 1000, "\r\n")) !== FALSE) {
    $table[$row][$cell] = $data[0];
    $row += $cell == 2 ? 1 : 0; //If its last cell, increase row, else do nothing
    $cell = $cell == 2 ? 0 : $cell+1; //if its last cell, reset to 0, else add 1
  }
  fclose($handle);
}

我希望它对你来说很容易理解

于 2012-05-02T20:11:26.147 回答
1

这是我的代码:

//filter for empty lines
function remove_empty($e){
if(trim($e)!="") return true;
}

//reading the csv file and building the integer array
$arr = array_filter(explode("\r\n",file_get_contents("test.csv")),"remove_empty");
//new array initialization
$newArr = array();
//selecting 3 values in one loop
for($i=0;$i<count($arr);$i=$i+3){
    $newArr[] = implode(",",array($arr[$i],$arr[$i+1],$arr[$i+2]));
}

print_r($newArr);
于 2012-05-02T20:25:17.693 回答