change value of a line in an array - php

I need to change the value of a line within an array to a given string, then implode and save the data. Im using the code below.
row is the row of the table.
target is the specific line in the array which i want to update.
nfv is the new string i want to put into the array.
<?
$rowpre = $_GET['row'];
$newfieldvalue = $_GET['nfv'];
$row = --$rowpre;
$data = file_get_contents("temp.php");
$csvpre = explode("###", $data);
$i = 0;
foreach ( $csvpre AS $key => $value){
$i++;
if($i = $row){
$info = explode("%%", $value);
$j = 0;
foreach ( $info as $key => $value ){
$j++;
if($j == $target){
/*change the value of this line to $newfieldvalue*/
}
}
}
}
$presave = implode("%%", $info);
$save = implode("###", $presave);
$fh = fopen("temp.php", 'w') or die("can't open file");
fwrite($fh, $save);
fclose($fh);
?>

You do realize that you can index into an array? If you already have the numeric index of an array element, just go ahead and change it:
$arr[$index] = "some new stuff";
Magically updated.

Related

Display array with array_search

I have an array of csv elements and I want to retrieve the key of the column 'Due Date' (the result is 10) and display the array at the column 10. However, it doesn't display the result but it will show the column 1 and I don't know why.
Code:
while (($line = fgetcsv($file)) !== FALSE) {
//$line is an array of the csv elements
$value = array_search('Due Date', $line);
print_r($line[$value]);
}
Just do it like this so you can easily get the column number 10:
$var = array();
while($row = fgetcsv($yourFile)) {
$var[] = $row;
}
//Get Column 10
$var[] = $row[9];
Edit:
<?php
$valueOfSearch = "YOUR VALUE OF SEARCH";
$linesOfCsv = file('YOUR PATH.csv');
$lineNumberOfCSV = false;
while (list($key, $line) = each($linesOfCsv) and !$lineNumberOfCSV) {
$lineNumberOfCSV = (strpos($line, $valueOfSearch) !== FALSE);
}
if($lineNumberOfCSV){
//Add YOUR CONDITION
}
?>
Open the fine and take csv values inside an array and close the file. After that try your logic.
So to get value you can use:
$file = 'file.csv';
$line = array();
$file = fopen($file,"r");
while(! feof($file))
{
$line = fgetcsv($file);
}
fclose($file);
$key = array_search('Due Date', $line);
print_r($line[$key]);

Group all lines with the same word in first column in csv

I have two columns in my csv file: first_column and second_column. I would like to group all the rows in second column into one string separated by "," if they all have the same word in the first column then output them into a text file.
first_column second_column
a Chris
a Jake
a Paula
b Anita
b Lionel
b Sheila
Desired output
a: Chris, Jake, Paula
b: Anita, Lionel, Sheila
This is what I tried. I seem to be only getting the first letter from the second_column. Any pointers would be great.
$csv_file = fopen("test.csv", "r");
$text_file = fopen("test.txt","w");
$data = array();
if ($csv_file)
{
while (($line = fgets($csv_file)) !== false)
{
$column_1 = $line[0];
$column_2 = $line[1];
if (!empty($column_1))
{
$data [$column_1] = column_2;
}
}
fclose($csv_file);
fclose($text_file);
}
else
{
// error opening the file.
}
//print_r($data);
This should work for you:
Here I first get your .csv file into an array with file(). Then I loop through each line and create an array, where the first column is the key and the second column a value of the sub array.
After this you can loop through your created array and implode() each sub array with the key to the expected line which you want. Then you can just save the data with file_put_contents() into your .txt file.
<?php
$csv_file = "test.csv";
$text_file = "test.txt";
$lines = file($csv_file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
array_shift($lines);
foreach($lines as $line) {
list($key, $value) = explode(",", $line); //Change your .csv delimiter here, if you use something else than ,
$data[$key][] = $value;
}
foreach($data as $key => $arr)
$content[] = $key . ": " . implode(",", $arr) . PHP_EOL;
file_put_contents($text_file, $content);
?>
Storing result in an data array and then wring it bacj to text file should work.
$csv_file = fopen("test.csv", "r");
$text_file = fopen("test.txt","w");
$data = array();
if ($csv_file)
{
while (($line = fgets($csv_file)) !== false)
{
$column_1 = $line[0];
$column_2 = $line[1];
if (!isset($data[$column_1]))
{
$data[$column_1] = column_2
} else {
$data[$column_1] = $data[$column_1] .',' . $column_2
}
}
foreach($data as $k=>$d ){
fputs($text_file, "$k: $d") ;
}
fclose($csv_file);
fclose($text_file);
}
else
{
// error opening the file.
}

PHP : POST-- How to replace defined KEY from ARRAY in a file

I'm a bit lost for I'm "green" in PHP.
Please, may you teach me how to fix this:
on 'POST' --> Replace a specified array key from a file:
(WRONG:)
<?php
$newData = $_POST["sendData"];
if(isset($_POST['sendData'])){
$file = fopen('fileToOpen.php', 'a');
foreach($file as $key => $val)
{
$data[$key] = explode("|", $val);
}
for($k = 0; $k < sizeof($file); $k++)
{
unset($data[$k][3]);
}
$data[$k][3] = "$newData";
fwrite($file, $data[$k][3]);
fclose ($file);
}
?>
That's wrong as it continues to write:
data1|data2|data3|oldDatanewData
instead of rewrite:
data1|data2|data3|newData
Is there any other technique to achieve something similar? Perhaps with file_put_contents? Am I missing implode?
Thanks!
Dunno what are you asking for but perhaps you only need to serialize and unserialize the array.
$data_array = unserialize(file_get_contents('fileToOpen.php'));
$data_array[$key_you_want_to_change] = $new_data;
file_put_contents('fileToOpen.php', serialize($data_array));
$newData = $_POST['sendData'];
if(isset($_POST['sendData'])){
$file = "fileToOpen.php";
$oldData = file_get_contents($file);
$oldData = eregi_replace("\n","",$oldData);
$FullDataArray = explode("?",$oldData);
$oldDataArray = explode("|",$FullDataArray[1]);
$oldDataArray[3] = $newData;
$newDataString .= "
foreach($oldDataArray as $key=>$val) {
$newDataString .= $val;
if($key!="3") {
$newDataString .= "|";
}
}
$fh = fopen($file, 'w');
fwrite($fh,$newDataString);
fclose($fh);
}
?>

How can I parse a CSV into array with first value as key?

So I have a CSV file that looks like this:
12345, Here is some text
20394, Here is some more text
How can I insert this into an array that looks like so
$text = "12345" => "Here is some text",
"20394" => "Here is some more text";
This is what I currently had to get a single numerical based value on a one tier CSV
if ($handle = fopen("$qid", "r")) {
$csvData = file_get_contents($qid);
$csvDelim = "\r";
$qid = array();
$qid = str_getcsv($csvData, $csvDelim);
} else {
die("Could not open CSV file.");
}
Thanks for the replies, but I still see a potential issue. With these solutions, wouldn't the values store in this way:
$array[0] = 12345
$array[1] = Here is some text 20394
$array[2] = Here is some more text
If I tried this on the example csv above, how would the array be structured?
You can use fgetcsv() to read a line from a file into an array. So something like this:
$a = array();
$f = fopen(....);
while ($line = fgetcsv($f))
{
$key = array_shift($line);
$a[$key] = $line;
}
fclose($f);
var_dump($a);
Assuming that the first row in the CSV file contains the column headers, this will create an associative array using those headers for each row's data:
$filepath = "./test.csv";
$file = fopen($filepath, "r") or die("Error opening file");
$i = 0;
while(($line = fgetcsv($file)) !== FALSE) {
if($i == 0) {
$c = 0;
foreach($line as $col) {
$cols[$c] = $col;
$c++;
}
} else if($i > 0) {
$c = 0;
foreach($line as $col) {
$data[$i][$cols[$c]] = $col;
$c++;
}
}
$i++;
}
print_r($data);
If you are reading a file I can recommend using something like fgetcsv()
This will read each line in the CSV into an array containing all the columns as values.
http://at2.php.net/fgetcsv
$csv_lines = explode('\n',$csv_text);
foreach($csv_lines as $line) {
$csv_array[] = explode(',',$line,1);
}
edit - based on code posted after original question:
if ($handle = fopen("$qid", "r")) {
$csvData = file_get_contents($qid);
$csvDelim = "\r"; // assume this is the line delim?
$csv_lines = explode($csvDelim,$csvData);
foreach($csv_lines as $line) {
$qid[] = explode(',',$line,1);
}
} else {
die("Could not open CSV file.");
}
With your new file with two columns, $qid should become an array with two values for each line.
$csvDelim = ",";
$qid = str_getcsv($csvData, $csvDelim);
$text[$qid[0]] = $qid[1];

invalid argument when imploding in php

Im getting invalid argument error when running the following code. Im trying to change the value of a line in the $info array, then implode it, implode its parent array, and then save the whole shebang back to whence it came.
$rowpre = $_GET['row'];
$newfieldvalue = $_GET['nfv'];
$row = --$rowpre;
$data = file_get_contents("temp.php");
$csvpre = explode("###", $data);
$i = 0;
foreach ( $csvpre AS $key => $value){
$i++;
if($i = $row){
$info = explode("%%", $value);
$info[$target] = $newfieldvalue;
$presave = implode("%%", $info);
}
}
$save = implode("###", $presave);
$fh = fopen("temp.php", 'w') or die("can't open file");
fwrite($fh, $save);
fclose($fh);
update below
$rowpre = $_GET['row'];
$newfieldvalue = $_GET['nfv'];
$target = $_GET['target'];
$row = --$rowpre;
$data = file_get_contents("temp.php");
$csvpre = explode("###", $data);
$i = 0;
foreach ( $csvpre AS $key => $value){
$i++;
if($i == $row){
$info = explode("%%", $value);
$info[$target] = $newfieldvalue;
$csvpre[$key] = implode("%%", $info);
}
}
$save = implode("###", $csvpre);
$fh = fopen("temp.php", 'w') or die("can't open file");
fwrite($fh, $save);
fclose($fh);
Target is the field within the selected Row that i wish to update with the newfieldvalue data.
$save = implode("###", $presave);
At that point, $presave is a string, and should be an array to work with implode. Create an array where you push the $presave-values, and implode that one.
$presave contains the last processed line (i.e. a string) and implode expects an array. To store the line back in the original array, change:
$presave = implode("%%", $info);
to:
$csvpre[$key] = implode("%%", $info);
And to convert the whole CSV array into a string, change:
$save = implode("###", $presave);
to:
$save = implode("###", $csvpre);
And one more problem:
if($i = $row){
should be:
if($i == $row){
because you want to compare the variables, not assign $i.

Categories