Call a single cell from a .CSV using PHP - php

I've a problem to import a single cell in csv,
i have a csv file that contain 7 column and ~1420 row,
i need to read only the 4 column number in 1420's row, how can i do it?
<?php
$url = "wp-admin/ftp/test.csv";
$csvData = file_get_contents($url);
$lines = explode("\n", $csvData);
$array = array();
foreach ($lines as $line) {
$array[] = str_getcsv($line);
}
echo $array[1];
?>
with this i have an array to output with all cell in one row,
but i need to take the third number in that row, and not all of it.

I believe $array is multidimensional the following should print what you want:
echo $array[1419][3];
Otherwise you can print it to check how it is structured:
print_r($array);
UPDATE: unidimensional
foreach ($lines as $line) {
$array[] = str_getcsv($line)[3];//PHP 5.4
}
echo $array[1419];

Related

PHP iterate through each row of csv and return row with matching element

I have a csv file called data.csv.
Here's a sample of what's in data.csv
Microsoft,2020-02-13,"Sample",tt,aa,qq,w,ee,rr,tt,", ",", ",", ","2020-02-13 16:03:08"
Google,2020-02-13,"HQ",tt,aa,qq,w,ee,rr,tt,", ",", ",", ","2020-02-13 16:10:48"
I'm trying to iterate through each row of the csv and check if user inputted variable (lets say var="Microsoft") matches the first value in any row. If it does match, then return all the elements in that row as an array. (tried this using fgetcsv but returns whole csv file)
Here's what I have tried so far:
foreach ($csv as $line) {
if ($line[0] == 'Microsoft') {
$file = fopen("data.csv","r");
echo(fgetcsv($file));
fclose($file);
}
}
$csv = array_map('str_getcsv', file('./temp.csv'));
foreach ($csv as $line) {
if ($line[0] == 'Microsoft') {
echo implode(', ',$line);
}
}
If the first column's value is suitable as an array index. You can use array_column to re-index by your first column:
<?php
$result = array_column(array_map('str_getcsv', file('data.csv')), null, 0)['Microsoft'] ?? null;

adding array into csv file - two array values on the same row different column

I have a php page that is creating a csv file for download which is made up of an array.
Short version of Array:
$data = array("Joe Bloggs", "jbloggs", "John Doe", "jdoe")
My array is made from output from other commands so i cant just change the layout of my array, i can make two arrays, one for names and one for usernames if that help achieve my goal.
This is what i am doing to add the array values into my csv file:
$output = fopen('php://output', 'wb');
fputcsv($output, array('Name', 'Username'));
foreach ($data as $line ) {
$val = explode(",", $line);
for ($i=0; $i<$val["count"]; $i++); {
fputcsv($output , array($val[$i]));
}
}
fclose($output);
This gives me a csv that looks like this:
Name | Username
Joe Bloggs|
jbloggs |
John Does |
jdoe |
Really i need to have the usernames on the same row but in the username column.
I have tried this and lots of variations on this but it does not seem to work, my thinking was i increase N by two each time so $i will be the name because it is every other index position and then when doing the fputcsv it would add 1 to $i so it would grab the username as it is the value after the name.
foreach ($data as $line ) {
$val = explode(",", $line);
for ($i=0; $i<$val["count"]; $i+=2); {
fputcsv($output , array($val[$i], $val[$i+1]));
}
}
fclose($output);
Using the above gives me all the values in column one still.
Apologies for the write my code style question but i am out of my depth on this and cant find how to get to two consecutive values in a for loop of an array.
Here is 1 way of doing it.
$output = fopen('php://output', 'wb');
fputcsv($output, array('Name', 'Username'));
$temp = []; //Define a temp array.
foreach ($data as $line ) {
$temp[]= $line;
if( count( $temp) == 2 ) { //If no. of values in temp array is 2, write to csv file
fputcsv($output , $temp );
$temp = []; //initialize $temp;
}
}
fclose($output);
You can use simply these two line codes.
for ($i=0 ;$i < count($data);$i+2) {
fputcsv($output , $data[$i],$data[$i+1]);
}

PHP Building an array with variables

I want to build an array to create a CSV file using variables. The $arraybuild variable will gather lines from a search so will never be the same amount of rows.
$arraybuild = "'aaa,bbb,ccc,dddd',";
$arraybuild .= "'123,456,789',";
$arraybuild .= "'\"aaa\",\"bbb\"'";
$list = array
(
$arraybuild
)
;
$file = fopen("contacts.csv","w");
foreach ($list as $line)
{
fputcsv($file,explode(',',$line));
}
fclose($file);
The problem is the result does not separate the lines, it places them all in the same line.
I want to get
aaa,bbb,ccc,dddd
123,456,789
"aaa","bbb"
What I am getting is
aaa bbb ccc dddd 123 456 789 "aaa" "bbb"
All in separate columns
Can someone please assist?
Push each rows to an array instead of concatenating to a string, then loop and add to csv
$arraybuild[] = "'aaa,bbb,ccc,dddd',";
$arraybuild[] = "'123,456,789',";
$arraybuild[] = "'\"aaa\",\"bbb\"'";
$file = fopen("contacts.csv","w");
foreach ($arraybuild as $line) {
fputcsv($file, explode(',', $line));
}
fclose($file);
In your code, you are concatenating all values to one string, separated by ,. After that, you are creating one array with one element in it (that long string).
So, it's not a surprise, that you are getting all of them on the same line.
To separate lines, you should create separate arrays inside the $list array. Each included array will be on the new line.
Try this:
<?php
$arraybuild1 = "'aaa,bbb,ccc,dddd',";
$arraybuild2 = "'123,456,789',";
$arraybuild3 = "'\"aaa\",\"bbb\"'";
$list = array
(
explode(',', $arraybuild1),
explode(',', $arraybuild2),
explode(',', $arraybuild3)
);
$file = fopen("contacts.csv", "w");
foreach ($list as $fields) {
fputcsv($file, $fields);
}
fclose($file);

Create combinations of 3 arrays

I'm trying to figure out how parse a multidimensional array/loop statement to lay out the iterated array values into rows (which will become a full row in a CSV file) The CSV file will end up with 24 rows based on below example
result
1999,apple,red
1999,apple,green
1999,orange,red
1999,orange,green
1999,strawberrry,red
... and so on
$year = array('1999','2000','2001','2002');
$fruit = array('apple','orange','strawberry');
$color = array('red','green');
You can use a foreach() loop and iterate over each of the 3 arrays and use fputcsv() to save the 3 items into a CSV file.
$fp = fopen('file.csv', 'w');
$year = array('1999','2000','2001','2002');
$fruit = array('apple','orange','strawberry');
$color = array('red','green');
foreach ($year as $y) {
foreach ($fruit as $f) {
foreach($color as $c) {
echo "$y,$f,$c" . PHP_EOL; // Echo to screen. Not needed
fputcsv($fp,array($y,$f,$c)); // Save each row to CSV file
}
}
}
fclose($fp);
Resulting file.csv file will then look like so:

Be sure to have unique array entry

I have a file which contains something like :
toto;145
titi;7
tata;28
I explode this file to have an array.
I am able to display the data with that code :
foreach ($lines as $line_num => $line) {
$tab = explode(";",$line);
//erase return line
$tab[1]=preg_replace('/[\r\n]+/', "", $tab[1]);
echo $tab[0]; //toto //titi //tata
echo $tab[1]; //145 //7 //28
}
I want to be sure that data contained in each $tab[0] and $tab[1] is unique.
For example, I want a "throw new Exception" if file is like :
toto;145
titi;7
tutu;7
tata;28
or like :
toto;145
tata;7
tata;28
How can I do that ?
Convert your file to array with file(), and convert to associative array with additional duplication checking.
$lines = file('file.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
$tab = array();
foreach ($lines as $line) {
list($key, $val) = explode(';', $line);
if (array_key_exists($key, $tab) || in_array($val, $tab)) {
// throw exception
} else {
$tab[$key] = $val;
}
}
Store them as key => value pairs in an array, and check whether each key or value already exists in your array as you are looping through the file. You can check for an existing key with array_key_exists and an existing value with in_array.
One simple is using array_unique, save the parts (tab[0] and tab[1]) into two separate arrays after you explode, name them for example $col1 and $col2 and then, you could do this simple test:
<?php
if (count(array_unique($col1)) != count($col1))
echo "arrays are different; not unique";
?>
PHP will turn your array parts into unique, if duplicated entrys exist, so if the size of the new array differs from the original, it means that it was not unique.
//contrived file contents
$file_contents = "
toto;145
titi;7
tutu;7
tata;28";
//split into lines and set up some left/right value trackers
$lines = preg_split('/\n/', trim($file_contents));
$left = $right = array();
//split each line into two parts and log left and right part
foreach($lines as $line) {
$splitter = explode(';', preg_replace('/\r\n/', '', $line));
array_push($left, $splitter[0]);
array_push($right, $splitter[1]);
}
//sanitise left and right parts into just unique entries
$left = array_unique($left);
$right = array_unique($right);
//if we end up with fewer left or right entries than the number of lines, error...
if (count($left) < count($lines) || count($right) < count($lines))
die('error');
Use associative arrays with keys "toto", "tata" etc.
To check whether a key exists you can use array_key_exists or isset.
BTW. Instead of preg_replace('/[\r\n]+/', "", $tab[1]), try trim (or even rtrim).
While you're traversing the array add the values to an existing array, i.e. placeholder, which will be used to check if the value exists or not via in_array().
<?php
$lines = 'toto;145 titi;7 tutu;7 tata;28';
$results = array();
foreach ($lines as $line_num => $line) {
$tab = explode(";",$line);
//erase return line
$tab[1]=preg_replace('/[\r\n]+/', "", $tab[1]);
if(!in_array($tab[0]) && !in_array($tab[1])){
array_push($results, $tab[0], $tab[1]);
}else{
echo "value exists!";
die(); // Remove/modify for different exception handling
}
}
?>

Categories