Putting csv file data into a level 2 array - php

I have been researching fgetcsv() and have the following working code:
$file = fopen($pathToCsv,"r");
$data = array();
while(! feof($file))
{
array_push($data, fgetcsv($file));
}
fclose($file);
However, when I try to adapt this to dynamically accept an unknown number of csv files stored into an array, things cease to work:
$year = $_POST['year'];
$m = "maths".$year;
$sheets = $$m; //an array containing between 5 an 8 paths to csv and other info
$data = array();
function ArrayFromCsv($file, $i) {
while(! feof($file))
{
array_push($data[$i], fgetcsv($file)); //line 15
}
fclose($file);
}
for ($i = 0; $i < count($$m); $i++){
array_push($data, array());
$x = fopen($sheets[$i]['csv'],'r');
ArrayFromCsv($x, $i);
}
I get: Warning: array_push() expects parameter 1 to be array, null given in ... on line 15
I'm not how to research this further. Is there a better way or obvious mistake? I've tried a number of methods.

You dont have access to the global $data variable inside of the function ArrayFromCsv. You either need to use "global $data" inside the function, which is bad, so DON'T
Or you could create a temporary array inside the function, which you return when the function ends and put the returned value from the function into $data[$i]. Also you should not open a file outside of a function and close it inside of a function. That could lead to undefined behaviour someday when your code gets bigger.

function ArrayFromCsv($file, $i) use (&$data) {
while(! feof($file))
{
array_push($data[$i], fgetcsv($file)); //line 15
}
fclose($file);
}

Related

php read and write file

function readWrite() {
$fileReader = fopen('file.txt', 'r') or die("ERROR: File not found");
$fileWriter = fopen('filewr.txt', 'w') or die ("ERROR: Write File not
found");
$totalDaysArr= array();
$monthNumArr= array();
$monthArr= array();
$row= file("file.txt");
while($row = fgets($fileReader, 4096)) {
list($monthNumArr[], $monthArr[], $totalDaysArr[]) = explode(",", $row);
}
for($x = 11; $x >= 0; $x--)
{
$table = explode(",", $monthNumArr[$x]);
fwrite($fileWriter, $row[$x]);
}
fclose($fileWriter);
}
I'm a beginner at PHP, so this is what I have so far. My objective is to make a function that will read a file called file.txt and then write it in reverse using arrays. I'm not sure what I am doing wrong here.
These are the requirements:
This function should use PHP array to store records (each line is a "record").
This function should use a PHP Loop to walk through the months names array and generate HTML5/CSS to display the table.
Create a function that writes the text file filewr.txt (reverse order).
This function should use PHP for loop to walk through the array in reverse order and write each array entry (line/record) to the filewr.txt file.
and also the txt file looks like this:
1,January,31
2,February,28
3,March,31
4,April,30
5,May,31
6,June,30
7,July,31
8,August,31
9,September,30
10,October,31
11,November,30
12,December,31
Why use fileReader when you decide to read the data with file("file.txt"); in the end?
The writing process is quite messed up fwrite($fileWriter, $row[$x]) is quite possibly the place where the error comes from: don't you aim to write that table to your file instead of a row from the original input file?
Addition
#Aureliux:
What you want to to is generating a HTML string.
Therefore, lets start with $table='<table>' and put this definition before the loop.
After the loop you add the tables closing tag: $table.='</table>'
The magic happens in between:
For each record you create the corresponding HTML representation.
$table.='<tr><td>'.$monthNumArr.'</td><td>'.$monthArr.'</td><td>'.$totalDaysArr.'</td></tr>'.
Finaly you move the write command after the loop and write the generated Table Markup to your output file.
What you will end up with looks like
function readWrite() {
$fileWriter = fopen('filewr.txt', 'w') or die ("ERROR: Write File not
found");
$totalDaysArr= array();
$monthNumArr= array();
$monthArr= array();
$row= file("file.txt");
while($row = fgets($fileReader, 4096)) {
list($monthNumArr[], $monthArr[], $totalDaysArr[]) = explode(",", $row);
}
$table='<table>';
for($x = 11; $x >= 0; $x--)
{
$table.='<tr><td>'.$monthNumArr.'</td><td>'.$monthArr.'</td><td>'.$totalDaysArr.'</td></tr>';
}
$table.='</table>';
fwrite($fileWriter, $table);
fclose($fileWriter);
}
I have no idea why you would need the reverse loop, but actually, you could achieve the same result with less effort:
function readWrite() {
$row= file("file.txt");
$table='<table>';
for($x = 11; $x >= 0; $x--)
{
$table.='<tr><td>'.implode('</td><td>', explode(',',$row[$x])).'</td></tr>';
}
$table.='</table>';
file_put_contents('file.txt', $table);
}
I did not test it. But the idea should be clear.
Personally, I would agree with #Alive to Die. His approach is the most straight forward.

PHP - How to transpose an array that is from a text file

We have made an array from a text file full of numbers separated by commas, each new line is a new part of the array. (we are not allowed to use explode for this)
We are trying to create a transpose_matrix function to 'transpose' the array now.
Using tutorials on the internet, this is what we have come up with so far, but it doesn't work :(
$myfile = fopen("text1.txt", "r") or die("Unable to open file!");
//echo fread($myfile,filesize("text1.txt"));
$file1 = file("text1.txt");
$store1 = array();
for ($a = 0; $a<count($file1); $a++)
{
array_push($store1, $file1[$a]);
}
for ($k = 0; $k<count($store1); $k++)
{
echo "Line $store1[$k] <br/> END <br/>";
}
function transpose($store1) {
$file1 = file("text1.txt");
$store1 = array();
if (count($store1) == 0) // special case: empty matrix
return array();
else if (count($store1) == 1) // special case: row matrix
return array_chunk($store1[0], 1);
function myCallbackMethod() {
var_dump ($store1);
}
array_unshift($store1, NULL); // the original matrix is not modified because it was passed by value
return call_user_func_array('myCallbackMethod',$store1);
}
transpose($store1);
fclose($myfile);
}
Try reading with fscanf().
something like
fscanf($file_link, '%s\n', $temp);
array_push($array, $temp);
should work.
Sukhdev Mohan

PHP Moving an array into different text files?

I've been given a list of data and I need to split it and move it into different text files. I've tried a few things so far but cant seem to get it to work.
<?php
/*
*order the file based on surname (col 2)
*create two new text files - class A and B
*split the source text into two equal lists
*format them: ID, firstname, lastname. all words must be first letter caps
*move each list to a new file.
*close files
*/
//This function converts every attribute/variable passed to it into a sentence case
function Uppercase($convert) {
return ucwords($convert);
}
//This function compares two items to see which one is higher
//src: http://php.net/manual/en/function.usort.php
function cmp($a, $b) {
$compResult = strcmp($a[1], $b[1]);
if ($compResult == 0) {
return strcmp($a[2], $b[2]);
}else {
return $compResult;
}
}
//This function gets rid of the whitespace that is not needed
function cut($c) {
return trim($c, " \n\r\0");
}
//open file
$myfile = fopen("students.csv", "r");
echo "A";
//initialise the array, giving them 'headers'
$array = array();
echo "B";
//sort through the data, moving it to a multidimentional array and setting the first letter in each item to uppercase
$i=0;
while(!feof($myfile)){
$line = fgets($myfile);
$pieces = explode(",", $line);
$array[$i][0] = $pieces[0];
$array[$i][1] = cut(Uppercase($pieces[2]));
$array[$i][2] = cut(Uppercase($pieces[1]));
$i++;
}
echo "C";
//sort the file by the second item in the array
usort($array, "cmp");
echo array_shift($array)."<br>";
echo "D";
//create class files
$fileA = fopen("Class 1.txt", "w");
$fileB = fopen("Class 2.txt", "w");
echo "E";
//get size of array
$arraylength = count($array);
//half the array length(
$half = ceil($arraylength /= 2);
//echo $half;
//echo $arraylength."</br>";
echo "F";
echo "<pre>";
print_r($array);
echo "</br>";
//move the first class into a text file
$k = 0;
foreach ($array as $key){
echo $key[0];
if ($k < $half) {
$current = file_get_contents($fileA);
$current .= $key;
}
}
echo "G";
fclose($fileA);
fclose($fileB);
fclose($myfile);
echo "H";
When this runs, I get the following line recurring for each item in the array
Warning: file_get_contents() expects parameter 1 to be a valid path, resource given in C:\xampp\htdocs\PHPLabs\EE1600Assignment.php on line 93
The document itself has 25 items that look like this:
123, billy, bobs
Any help is appreciated. Thank you
file_get_contents expects a file path, but you are providing a file handler. You probably want instead fgets($fileA).
Alternatively, if you want to read the complete file (it's not entirely clear from your code), you can use fread($fileA).
According to the documentation, file_get_contents requires a path to the file you want to open (as per the error message you're getting - file_get_contents() expects parameter 1 to be a valid path).
You're passing in $fileA - which you created earlier using an fopen call
fopen("Class 1.txt", "w");

Error: First argument should be an array in

I have this code and no code before it that refers to any variables seen below. Yet I still can't find why I'm getting the error: "First argument should be an array in..."
$array = array("element here for reason");
function sortdata()
{
$File = fopen("Names.txt", "r");
//put each file line into an array element
while(!feof($File))
{
array_push($array, fgets($File));
}
}
$array is out of scope to the function. You can bring it into scope using global.
$array = ..;
function sortdata() {
global $array;
...
}
sortdata();
Alternatively, you can pass it by reference into the function.
$array = ..;
function sortdata(&$array) {
...
}
sortdata($array);
You use variable $array inside function body. In this case this is local variable and it automatically sets to string.
For work with your global variable $array you should use instruction global in your function.
function sortdata() {
global $array;
/* there your code for work with $array */
}
The issue with the code is that you are not passing the $array variable into the function. Aside from that, it would be more efficient to use the shortcut way to add an item to the array instead of calling array_push since it eliminates the overhead of calling a function.
$array = array("element here for reason");
function sortdata($array)
{
$File = fopen("Names.txt", "r");
//put each file line into an array element
while(!feof($File))
{
$array[] = fgets($File);
}
return $array;
}
You should try to first initialize the array and bring the array within the scope of the function like so:
$array = array();
array_push($array, "element here for reason");
function sortdata()
{
global $array;
$File = fopen("Names.txt", "r");
//put each file line into an array element
while(!feof($File))
{
array_push($array, fgets($File));
}
}
This give you backward compatibility
function sortdata(array $array = array())
{
$File = fopen("Names.txt", "r");
while(!feof($File))
{
array_push($array, fgets($File));
}
return $array;
}

how to read text file and translate fild

Hello, how to read txt file using php and replacement with array?
i want read file like this:
||Search||,||s||---||Images||,||i||
this my php code:
$f = fopen("test.txt", "r");
$image= "Imgaes";
// Read line by line until end of file
while (!feof($f)) {
// Make an array using comma as delimiter
// $arrM = explode("---",fgets($f));
$arr = explode("||---||",fgets($f));
// Write links (get the data in the array)
$num = 1;
while($num <= 30) {
list($eng,$fa) = explode("||,||", $arr[$num]);
foreach($html->find('html') as $full) {
$all = $full->innertext;
}
$fe = str_replace($eng,$fa,$all);
$num = $num+1;
}
echo $fe;
}
fclose($f);
but this not work:(!!!
before the explode, parse your data in this function:
// Function arrayData
function arrayData($data){
# code...
// Create an array out of each line
$data_array=explode("\n", $data);
// Find the last key in the array
$last_key=count($data_array)-1;
// If the last line is empty revise the last key downwards until there's actually something there
while(empty($data_array[$last_key]))
{
$last_key-=1;
}
// Figure out the first key based upon the value set for the number of lines to display
$first_key=$last_key-($this->num_lines-1);
// Start a new array to store the last X lines in
$final_array=array();
// Work through the array and only add the last X lines to it.
foreach($data_array as $key => $value)
{
if($key >= $first_key && $key <= $last_key)
{
$final_array[]=$value;
}
}
return $final_array;
} // end function

Categories