读取文件,并将数字添加到数组部分

时间:2012-05-02 20:04:02

标签: php arrays multidimensional-array fread

我有一个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 个答案:

答案 0 :(得分: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);
?>

答案 1 :(得分: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);

答案 2 :(得分: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);
}

我希望你很容易理解

答案 3 :(得分: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);