Прочитайте файл и добавьте числа в массивные части.

У меня есть 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, чтобы получить результат, который я хочу. Не могли бы вы помочь?

Solutions Collecting From Web of "Прочитайте файл и добавьте числа в массивные части."

Используйте это, я тестировал и работает:

 <?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); ?> 

Меньший (даже если вы уже приняли другой ответ), но не означает, что он «лучше» (поскольку он не так легко читается). Тем не менее вы можете узнать некоторые трюки:

 $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); 

Вы должны объявить ячейку вне цикла или она будет всегда перезагружена …

Вот требуемый код:

 $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); } 

Я надеюсь, что его легко понять для вас

И вот мой код:

 //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);