Error when trying to access a 2d Array in PHP - php

I have written a couple pages and some function to turn a .csv file into an array, after which I will be using the array to access and use the data. Most of the code is in place and works but I am stuck with trying to access the fields I want.
The code to create the array looks like this:
//code for accepting and checking the uploaded file
if($ext === 'csv'){
if(($handle = fopen($tmpName, 'r')) !== FALSE) {
set_time_limit(0);
//index
$row = 0;
while(($data = fgetcsv($handle, 1000, ',')) !== FALSE) {
// number of fields in the csv
$num = count($data);
/*echo "<p> $num fields in line $row: <br /></p>\n";*/
// get the values from the csv
$csv[$row]['row1'] = $data[0];
$csv[$row]['row2'] = $data[1];
$csv[$row]['row3'] = $data[2];
$csv[$row]['row4'] = $data[3];
//increment
$row++;
}
print_array($csv[1][0]);
fclose($handle);
}
}
And when I call something like print_array($csv[1]; The result is:
Array
(
[row1] => DataOne
[row1] => DataTwo
[row1] => DataThree
[row1] => DataFour
)
But when I call print_array($csv[1][1]); I get the error: Notice: Undefined Offset: 1 On line *and so on*
Everything I have read makes it seem like this should work. I can't figure out how to get access to what I need. Any help appreciated.

Try to check how many elements your Array have looks to me like it just read the first line and your Array length is 1.
echo("Array count: ".count($csv));

Related

PHP uploading CSV file and using first line as the KEYS instead of 0,1,2

I am working on a CSV file upload function. The whole script is working fine and the way I am doing it is by eliminating the first line of the CSV file which is the heading and then using the data only to insert into the database. However, this adds a restriction for the CSV to be sorted always. I need to accept unsorted CSV too. For example, if a column name is in second column and of the CSV file then the array index becomes $arr[1]. Currently, I am using $arr[1] for inserting the values in the database and performing operations. This is bad. If the user uploads an unsorted CSV where name is in 4th column and say phone is in 2nd column where earlier I expected the name to be, then this will disrupt the whole operation. Therefore, how can I use the first heading line and use them as a key like $arr['name'] for performing the required operations?
My current code:
$csvFile = fopen($_FILES['file']['tmp_name'], 'r');
fgetcsv($csvFile);
$arr = [];
while($data = fgetcsv($csvFile, 100, ",")){
$arr['id'] = $data[0]; // WANT TO USE $data['id'] FROM CSV FILE's FIRST LINE
$arr['date'] = date('Y-m-d', strtotime($data[1])); // WANT TO USE $data['date'] FROM CSV FILE's FIRST LINE
$arr['stock'] = $data[2]; // WANT TO USE $data['stock'] FROM CSV FILE's FIRST LINE
$arr['price'] = $data[3]; // WANT TO USE $data['price'] FROM CSV FILE's FIRST LINE
$ar[] = $arr;
}
fclose($csvFile);
How can I get the keys from the file and use it here in the code above?
UPDATE
I see that if I store the keys in array and print it like this
$csvFile = fopen($_FILES['file']['tmp_name'], 'r');
$getFileKeys = fgetcsv($csvFile); // STORED KEYS IN ARRAY
fgetcsv($csvFile);
print_r($getFileKeys);
then I get an array like this:
Array
(
[0] => id
[1] => date
[2] => stock_name
[3] => price
)
I need to write logic in such a way that if I have 4 variables one for each of the element above, then no matter if the index changes for any element, the variable will receive the same value dynamically.
Since you already got the keys inside $getFileKeys variable you can simply use a for loop to loop through the array of keys and dynamically assign the indexes based upon the field.
$getFileKeys = fgetcsv($csvFile);
$keys = [];
for($i = 0; $i < count($getFileKeys); $i++){
if($getFileKeys[$i] == 'id'){
$keys['id'] = $i;
}else if($getFileKeys[$i] == 'date'){
$keys['date'] = $i;
}else if($getFileKeys[$i] == 'stock_name'){
$keys['stock'] = $i;
}else if($getFileKeys[$i] == 'price'){
$keys['price'] = $i;
}
}
while($getData = fgetcsv($csvFile, 100, ",")){
$arr['id'] = $getData[$keys['id']];
$arr['date'] = date('Y-m-d', strtotime($getData[$keys['date']]));
$arr['stock'] = trim($getData[$keys['stock']]);
$arr['price'] = $getData[$keys['price']];
$ar[] = $arr;
}
The $keys array now dynamically stores the indexes for each key. Therefore, this now sorts the CSV file no matter at what order which column is placed in.
You could make variables out of the first line, so that you can call them by her name.
$exampleLine=[
'id' => 1
'date' => '2022-07-01'
'stock_name' => 'stock_name'
'3' => 'price'
];
foreach($exampleLine as $name){
$$name=$name;
}
This will give you the variables with appropriate content, so that $id contains 1, $date '2022-07-01' and so on.
to prevent different spellings, you could still use lcfirst and trim.
PHP-Manual

Data from CSV placed behind each other in array (PHP array)

I'm currently having trouble with reading data from a CSV file. Now it shows the data from the CSV file like this when I print the array.
Array
(
[0] => james;large;33
)
However I want it to have it like this
Array
(
[0] => james
[1] => large
[2] => 33
)
This is the code that I'm using to read data from the CSV file
$file = fopen($file, 'r');
while ($row = fgetcsv($file) ) {
print "<pre>";
print_r($row);
print "</pre>";
}
And this is the CSV file that I'm using:
Any suggestions how I can make this work like I want to? Thanks in advance!
You have different delimiter used in CSV rather default which is ,
fgetcsv
you can define delimiter in fgetcsv function as a second parameter.
$file = fopen($file, 'r');
while ($row = fgetcsv($file, 0, ";") ) {
print "<pre>";
print_r($row);
print "</pre>";
}

Trying to process information from .csv file into PHP

I'm trying to pull information from a .CSV file to process with PHP into a local database.
I have the following code:
<?
$csv = array_map('str_getcsv', file('red.csv'));
echo $csv[1];
?>
The first bit works, if I try to echo the array_map with print_r or var_dump - but I'm not sure how to process it this way.
I'm used to being able to loop through with a for loop where $csv is an array and [0] is the record - but right now the only thing being ECHO'd is Array
I've never worked with array_map's before - and I found the code I am using (Except for the echo obviously) elsewhere online.
How can I loop through the entire array to process each record individually?
The reason Array is being echoed is because str_getcsv returns an array. So $csv is an array with each element inside it being an array of the csv values. If you change it to
<?php
$csv = array_map('str_getcsv', file('red.csv'));
print_r($csv[0]);
?>
You will be able to see the line as an array of each csv item.
You can loop through csv with this:
if (($handle = fopen("your.csv", "r")) !== FALSE) {
while (($data = fgetcsv($handle, null, ";", '"')) !== FALSE) {
// $data is an array that contains the current row
}
}
note: change the delimiter and escape characters in fgetcsv() according to your csv.
You can travel/iterate over the CSV array using this structure:
foreach( $csv as $row_id => $row_data ) {
foreach( $row_data as $cell_id => $cell_data ) {
// The next will output the same data
echo $cell_data . '\n';
echo $csv[$row_id][$cell_id] . '\n';
}
}
Please follow below code for getting data from csv, looping through each row.
<?php
$csv = array_map('str_getcsv', file('red.csv'));
//print_r($csv[0]);
foreach($csv as $key=>$v)
{
echo $csv[$key][0];//column A/0
echo $csv[$key][1];//column B/1
}
?>

Fill array with contents of csv with php

I am trying to fill a array with a csv so each field is separate part of the array, when i have filled the array and echo it out it quite literally says array for every enter.
I have a feeling that once i sort the csvfull array that the sku might need to be in loop inside the main processing loop to.
$ocuk = fopen("ocuk.csv", "r");
while (($result = fgetcsv($ocuk)) !== false)
{
$csvfull[] = $result;
}
print_r ($csvfull[0][1]);
$sku="$csvfull[1]";
while (($csv = fgetcsv($ocuk)) !== FALSE)
{
if (false === empty(array_intersect($sku, $csv)))
{
code to display the results from csv that match the $sku variable
}
}
What i need it to do is csvfull array to fill with the contents of the csv such i can then call it into the variable sku to do comparison in next part of the code.
EDIT example of what i mean
csv example
data,data2,data3,data4 etc
data10,data20,data30,data40 etc
the array would then be like this
$csvfull=array() would contain the below
array("data","data2","data3","data4");
array("data10","data20","data30","data40");
then when i call csvfull[1] it display data2 then would go onto data 20 etc
$csvfull is a 2-dimensional array. The first dimension is the rows of the CSV, the second dimension is the columns. So $csvfull[1] is an array containing all the values from the second line of the file. To get the SKU, you need to drill down to the appropriate column, e.g.
foreach ($csvfull as $row) {
$sku = $row[1];
// Do something with $sku
}
If you want to get an array of all the SKUs, you can do:
$sku = array();
foreach ($csvfull as $row) {
$sku[] = $row[1];
}
try like this:
<?php
$ocuk = fopen('clientes.csv','r');
$i=0;
while(!feof($ocuk)){
$values = fgetcsv($ocuk);
if(empty($values[1] )){ // any index which is not empty to make sure that you are reading valid row.
continue;}
$csvfull[$i] = $values;
$i++;
}
print_r($csvfull);
.
fclose($ocuk);

Count number of similar values in CSV column

I have several .csv files that I am trying to loop through and read the values of a specific column as well as count how often each value appears. For example, the third column in one of the files, we'll call it $col[2], looks like this:
HEADER
foo
bar
bar
bar
foo
I can count the number of times both foo and bar appear in the file using this code:
$file = ('Path/To/Random/File.txt');
$fh = fopen($file, 'rb');
$tag = array();
while($col = fgetcsv($fh)) {
$tag[$col[2]]++;
}
print_r($tag);
Result:
5
But, this code returns the count for all of the values in col[2] . How can I specify that I want the number of foo and bar values, only split into which count belongs to which value? For example, the result would look something like this:
echo $foo_count;
echo $bar_count;
Result:
2
3
I would do:
$file = ('Path/To/Random/File.txt');
$fh = fopen($file, 'rb');
$tag = array();
while($col = fgetcsv($fh)) {
if (isset($tag[$col[2]])) {
$tag[$col[2]]++;
}
else {
$tag[$col[2]] = 1;
}
be sure $col[2] actually contains the value you want to measure/iterate
once that you should have an array like, use print_r to check
'foo' => 2,
'bar' => 3

Categories