I am trying to add data to 2 different MySql tables through a CSV upload. I have been able to retrieve the information and upload part of the information on one table, but I am having issues sending data to the second table. I have come up with the following code:
$i = 0;
//Loop through the csv file
do {
if ($data[0]) {
//Store request information
//Info for Request Table
$requester_email = $data[0];
$requester_name = $data[1];
$client_name = $data[2];
$client_country = $data[3];
$opportunity_number = $data[4];
$machine_quantity = $data[5];
$severity = $data[6];
//Store machine values
//Info for Serial Numbers Table
$serialType = array();
$serialModel = array();
$serialType[$i] = $data[7];
$serialModel[$i] = $data[8];
}
$i++;
} while ($data = fgetcsv($handle,1000,",","'"));
I am having an issue with the array. I have only been able to store the serialType and serialModel from the last line in the csv file. For example, if the csv file has 3 lines of data:
(
[0] => Empty
[1] => Empty
[2] => Last Value ok
)
How come I am unable to store the other two values?
Just move
$serialType = array();
$serialModel = array();
before do in your script. While it is still inside the do loop it is just a initialize variable in do - while scope each iteration and clean it up.
$i = 0;
$serialType = array();
$serialModel = array();
while ($data = fgetcsv($handle,1000,",","'")) {
...
$serialType[$i] = $data[7];
$serialModel[$i] = $data[8];
$i++;
};
Related
I have a phone book array I get from a database, where everyone appears once with their stationary phone number and a second with their mobile number.
I need to make this an array where everyone has only one line, with their phone number and mobile number
//My array
$data = array(
array('name'=>'robert','family'=>'bridgstone','home'=>'0258101234'),
array('name'=>'robert','family'=>'bridgstone','phone'=>'07258101235'),
array('name'=>'dan','family'=>'swartz','home'=>'098101244'),
array('name'=>'ben','family'=>'wais','home'=>'0447256155778'),
array('name'=>'ben','family'=>'wais','phone'=>'04472861558878'),
);
//The result that should come out
$data = array(
array('name'=>'robert','family'=>'bridgstone','home'=>'0258101234','phone'=>'07258101235'),
array('name'=>'dan','family'=>'swartz','home'=>'098101244','phone'=>''),
array('name'=>'ben','family'=>'wais','home'=>'0447256155778','phone'=>'04472861558878')
);
I would do it the following way:
first I would generate a unique key that identify the row (in your case the name and the family, for example).
then check if a element with the same key exist, if it already exist merge the two component.
Optional if you only want an array of values transform the result with array_value function.
$dataArray = array(
array('name'=>'robert','family'=>'bridgstone','home'=>'0258101234'),
array('name'=>'robert','family'=>'bridgstone','phone'=>'07258101235'),
array('name'=>'dan','family'=>'swartz','home'=>'098101244'),
array('name'=>'ben','family'=>'wais','home'=>'0447256155778'),
array('name'=>'ben','family'=>'wais','phone'=>'04472861558878'),
);
$result = [];
foreach($dataArray as $data){
//Just in case that the name or the family is not assigned (operator ??)
$key = ($data['name']??'').'-'.($data['family']??'');
$result[$key] = array_merge($result[$key]??[],$data);
}
//Optional, get only the array values
$result = array_values($result);
I did so
$data = array(
array('name'=>'robert','family'=>'bridgstone','home'=>'0258101234'),
array('name'=>'robert','family'=>'bridgstone','phone'=>'07258101235'),
array('name'=>'dan','family'=>'swartz','home'=>'098101244'),
array('name'=>'ben','family'=>'wais','home'=>'0447256155778'),
array('name'=>'ben','family'=>'wais','phone'=>'04472861558878'),
);
count($data) < 2 ? exit(): $data;
for($i=0;$i<count($data);$i++){
$array_unique[$i] = $data[$i]["name"];
$array_unique[$i] = $data[$i]["family"];
}
$array_unique = array_unique($array_unique);
if(count($array_unique) == 1){
$last_array[0]=$array_unique[0];
$last_array[0]["phone"]=$array_unique[0]["phone"];
}
else{
$array_uniqueKeys = array_keys($array_unique);
for($i = 0;$i < count($array_unique);$i++){
$firstIndex = $i + 1;
$firstIndex == count($array_unique) ? $nextKey = count($data) : $nextKey = $array_uniqueKeys[$firstIndex];
$paar = $nextKey - $array_uniqueKeys[$i];
$dataslice = array();
$i3=0;
for($i2 = $array_uniqueKeys[$i];$i2 < ($array_uniqueKeys[$i]+$paar);$i2++){
if(in_array($i2,$array_uniqueKeys)){
$last_array[$i]=$data[$i2];
}
else{
$last_array[$i]["phone"]=$data[$i2]["phone"];
}
$i3++;
}
}
}
print_r($last_array);
I have a csv file where the first line shows the name of each row. This name should be the key for an associative array. Currently I am pulling this in manually and if the row order changes it will break the functionality.
How can I retrieve the names from line 1 and create keys out of it?
$csv = array();
$index = 0;
while ($row = fgetcsv($fp)) {
if ($row[0] == NULL)
continue;
else{
$index++;
foreach($row as $csvdata){
list(
$csv[$index]['column 1 name'],
$csv[$index]['column 2 name']
)
= explode(';',$csvdata);
}
}
}
Try converting the very first line of the file, which contains the names/keys, into an array. Then use those keys to populate the associate array as you parse the remaining lines.
$keys = array();
$csv = array();
$index = 0;
while ($row = fgetcsv($fp)) {
if ($index == 0) {
$keys = explode(',', $row);
}
else {
$csv[$keys[index-1]] = $row;
}
++$index;
}
This answer assumes that what you want here is an associate array where the keys correspond to the names in the first row, and the values correspond to each row in the CSV import.
I have csv file with 1500+ entries in a column.I can able to read csv file's all values of column with this.
$rowcount = 1;
$srcFileName = "input/test.csv";
$file = fopen($srcFileName,"r");
$inputfielscount = count(file($srcFileName, FILE_SKIP_EMPTY_LINES));
while($rowcount < $inputfielscount)
{
$row = fgetcsv($file);
$result=array("id" =>$row[0],"des"=>"I am jhon",salery="10000");
$Final=array("listingsEmp"=>$result);
}
After reading first (1-10) value i will create an array (like array [0] =>$result) and Then wantto repeat same task from (11-20) and create another array (like array [1] =>$Final this time $final array contain information about the next ids whic we read from csv file (11-10)) and so on.
For the above requirment i changed code to this :
$rowcount = 1;
$srcFileName = "input/test.csv";
$file = fopen($srcFileName,"r");
while($rowcount < 20)
{
if(($rowcount % 10 == 0) && ( $rowcount != 0)) {
$rowcount++;
break;
}else{
$row = fgetcsv($file);
// some curl code for fetching data according to csv file field(Id)
$result=array("id" =>$row[0],"des"=>"I am jhon",salery="10000"); //contain 10 array
}
}
$Final=array("listingsEmp"=>$result);
Now i will post this $final array which has (0-10 index array ,each has unique id and corresponding values) using curl and get response which i am save in csv file.
$currenttime=date("Y-m-d-H_i_s");
$opfile='output'.$currenttime.'.csv'; //path wher op csv file exist
if(!#copy($srcFileName,'/output/'.$opfile))
{
$errors= error_get_last();
echo "COPY ERROR: ".$errors['type'];
echo "<br />\n".$errors['message'];
}else { // echo "File copied from remote!";
$fp = fopen('output/output'.$currenttime.'.csv',"a");
$fr = fopen($srcFileName,"r");
$rowcounts=0;
$FinalRES=$Final->response;
while($rowcounts< $inputfielscount) {
$resultBulk=$FinalRES[$rowcounts];
$resultBulkStatus=$FinalRES->status;
$resultBulkErrors=$FinalRES->errors;
$errorMsgArray=$resultBulkErrors[0];
$BulkErrorsMessage=$errorMsgArray->message;
$rows = fgetcsv($fr);
if($resultBulkStatus=='failure'){
$list = array ($rows[0],$rows[1],$resultBulkStatus,$BulkErrorsMessage);
}else {
$list = array ($rows[0],$rows[1],$resultBulkStatus,"successfully");
}
fputcsv($fp,$list);
//$p++;
$rowcounts++;
}
}
This full code runs once and give response for 10 ids ,i want repeat this code again for next 10 id (11-20)and then for (21-30) so on .
Once all response write in output csv file After that it display download output file link,Output file contain full response for all Ids which is in csv file(1500 +)
<?php $dnldfilw='output'.$currenttime.'.csv';?>
<a href='download.php?filename=<?php echo $dnldfilw; ?>'>Download Output file</a>
?>
The easiest method is to just use the file() function you are already using...
So to shorten the code to some pseudocode:
<?php
$indexedArray = array();
$indexedSplit = 10;
$lines = file($srcFileName);
$tempArray = array();
foreach($lines as $line) {
if(count($tempArray) % $indexedSplit === 0) {
$indexedArray[] = $tempArray;
$tempArray = array();
}
$tempArray[] = $line;
}
foreach($indexedArray as $index => $valueArray) {
// do the curl magic
// write results of curl into csv
}
Your question is poorly phrased, but I think this would be your aim, right?
In the $csv_array_attributes[0] represents every column for my csv file. sku is the product id. In $csv_array_attributes[0] represents all of the product ids for my csv(which is the rows value form column sku). In the query below I extract all of the products ids, attributes names and attributes values. My problem is that I have to compute my $csv array in order to assign for each attribute name(columns) the attribute values. In $final_string somehow I want to memorize all of the attributes values for a products (see the commented part). Thx in advance for the help. Im really stuck with this :(
$csv_array_attributes[0] = "sku%%".$header;
//GETTING ATTRIBUTES VALUES
$i = 1;
foreach($xml->children() as $content){
$id_produs = $content->ProductCode;
$csv_array_attributes[$i] = $id_produs;
$i++;
}
$select = mysql_query("SELECT id_prod.id_produs, GROUP_CONCAT('^^',nume_attr) AS nume_at, GROUP_CONCAT('^^',val_attr) AS val_at FROM attributes
INNER JOIN id_prod
ON id_prod.id_id_produs = attributes.id_produs
GROUP BY id_prod.id_produs");
$i = 0; $id_prod = array();
while ($row = mysql_fetch_array($select)){
$id_produs = $row['id_produs'];
$nume_attr = explode(",^^",substr($row['nume_at'],2));
$val_attr = explode(",^^",substr($row['val_attr'],2));
$id_prod[$id_produs] = $nume_attr;
$i++;
}
// var_dump(count($id_prod));
$nume = explode("%%", $csv_array_attributes[0]);
$csv[0] = $csv_array_attributes[0];
$i = 1;
foreach ($id_prod as $key => $value) {
// comment part
//$final_string = "";
//if (attr_name has attribute_value for product i ){
// $final_string.= attribute_value."%%";
//}else{
// $final_string.= "%%";
//}
//end comment part
$csv[$i] = $csv_array_attributes[$i]."%%".$final_string;
$i++;
}
//var_dump($csv_array_attributes[0])
//CREARE CSV
$file = fopen("attributes.csv","w+");
foreach ($csv as $line){
fputcsv($file,explode('%%',$line),"^","`");
}
To see the current result please click HERE
Actually I only can give you a hint how I would create a array for csv.
// header
$csv[0][0] = "one";
$csv[0][1] = "two";
$csv[0][2] = "three";
$csv[0][3] = "four";
$csv[0][4] = "five";
// body
$csv[1][0] = "some";
$csv[1][1] = "values";
$csv[1][2] = "that";
$csv[1][3] = "could";
$csv[1][4] = "be";
$csv[2][0] = "here";
$csv[2][1] = "in";
$csv[2][2] = "this";
$csv[2][3] = "little";
$csv[2][4] = "array";
This is only a sample to view the array setup.
If you have set up the header, lets say by a for you can fill the 2 demensional array.
If this is set up you can use a foreach to build your CSV
Sample
$seperator = ";";
$ln = "\r\n";
$csv_output = "";
foreach($csv as $c){
foreach($c as $value){
$csv_output .= $value . $seperator;
}
$csv_output . $ln;
}
csv output
one;two;three;four;five;
some;values;that;could;be;
here;in;this;little;array;
a row;with an;;empty;field;
empty fields are no problem since you seperate them all with a ;
I'd like to think that there's a simple way of doing this. I have over thirty columns in a database that I need to update. All of the columns have the same name as the correlating session variables.
Here's my code to fetch the array and assign variables:
while ($row = mysql_fetch_array($result))
{
$_SESSION['PendingCivil'] = $row['PendingCivil'];
$_SESSION['PendingAsbestos'] = $row['PendingAsbestos'];
$_SESSION['PendingDomestic'] = $row['PendingDomestic'];
$_SESSION['AsgNewCivil'] = $row['AsgNewCivil'];
$_SESSION['AsgNewAsbestos'] = $row['AsgNewAsbestos'];
$_SESSION['AsgNewDomestic'] = $row['AsgNewDomestic'];
$_SESSION['AsgTransferCivil'] = $row['AsgTransferCivil'];
$_SESSION['AsgTransferAsbestos'] = $row['AsgTransferAsbestos'];
$_SESSION['AsgTransferDomestic'] = $row['AsgTransferDomestic'];
$_SESSION['AsgReopenedCivil'] = $row['AsgReopenedCivil'];
$_SESSION['AsgReopenedAsbestos'] = $row['AsgReopenedAsbestos'];
$_SESSION['AsgReopenedDomestic'] = $row['AsgReopenedDomestic'];
$_SESSION['DispWOPCivil'] = $row['DispWOPCivil'];
$_SESSION['DispWOPAsbestos'] = $row['DispWOPAsbestos'];
$_SESSION['DispWOPDomestic'] = $row['DispWOPDomestic'];
$_SESSION['DispFinalCivil'] = $row['DispFinalCivil'];
$_SESSION['DispFinalAsbestos'] = $row['DispFinalAsbestos'];
$_SESSION['DispFinalDomestic'] = $row['DispFinalDomestic'];
$_SESSION['DispBTCivil'] = $row['DispBTCivil'];
$_SESSION['DispBTAsbestos'] = $row['DispBTAsbestos'];
$_SESSION['DispBTDomestic'] = $row['DispBTDomestic'];
$_SESSION['DispJTCivil'] = $row['DispJTCivil'];
$_SESSION['DispJTAsbestos'] = $row['DispJTAsbestos'];
$_SESSION['DispJTDomestic'] = $row['DispJTDomestic'];
$_SESSION['DispTOCivil'] = $row['DispTOCivil'];
$_SESSION['DispTOAsbestos'] = $row['DispTOAsbestos'];
$_SESSION['DispTODomestic'] = $row['DispTODomestic'];
$_SESSION['OldCivil'] = $row['OldCivil'];
$_SESSION['OldAsbestos'] = $row['OldAsbestos'];
$_SESSION['OldDomestic'] = $row['OldDomestic'];
}
Basically I'd like to update each row with a (possibly) changed session variable on an update page. Is there a way to iterate through the session variables and update the corresponding columns? Note: I have other session variables set that are not in the DB.
What about:
while ($row = mysql_fetch_assoc($result))
foreach($row as $k => $v)
$_SESSION[$k] = $v;
fetch them all to associative arrays
while ($row = mysql_fetch_assoc($result)){
foreach($row as $column_name => $data){
$_SESSION[$column_name] = $data;
}
}