I am using PHPExcel with Symfony 2 and showing the content of an excel file like this:
$users = array();
foreach($excel as $i=>$row) {
if($i !== 1) {
array_push($users,array(
'row'=>$i,
'name'=>$row['A'],
'lastname'=>$row['B']
//...and so on
));
}
}
Question:
How can I show the content using the row name instead of $row['A']..ect?
As $row['name']... I mean the name of the excel row.
Example:
A = name B = email...and so on...
I would like to show the content like this:
$users = array();
foreach($excel as $i=>$row) {
if($i !== 1) {
array_push($users,array(
'row'=>$i,
'name'=>$row['name'],
'lastname'=>$row['surname']
//...and so on
));
}
}
I'm pretty sure that I answered this question barely a week ago.... assuming that row #1 contains your headers:
if($i == 1) {
$headers = $row;
} else {
$row = array_combine($headers, $row);
array_push($users,array(
'row'=>$i,
'name'=>$row['name'],
'lastname'=>$row['surname']
//...and so on
));
}
Related
I want this sql-query result (from a log file, i hope it's accurate)
[
{"id":"1","text":"123"}
,{"id":"2","text":"456"}
] []
to become this
{
1: {"id":"1","text":"123"}
,2: {"id":"2","text":"456"}
}
I tried array_push and array_combine but am new to PHP and was unsuccessful so far.
Short: I want to add keys (starting with 1) to an array of objects.
One attempt
$i = 1;
while ($row = fetchRow($result)) {
array_push($arr_result, $row);
array_push($i, $arr_result);
$i++;
}
But $arr_result looks like the first code sample.
You dont need $i using $arr_result[] will create a new occurance in your array.
while ($row = fetchRow($result)) {
// this forces the array to start at 1 instead of 0 if thats what you really want
if (count($arr_result) == 0){
$arr_result[1] = $row;
} else {
$arr_result[] = $row;
}
}
Or if the key is supposed to be the id from the row
while ($row = fetchRow($result)) {
$arr_result[$row['id']] = $row;
}
I'm struggling with GFAPI's function submit_form() when it's used in loops. For unknown reason it often merges data from other loops into one, the outcome of this situation is that only the very first entry is added in a proper way, the rest seems to be empty.
I can't use other function although I've tried - and it worked (add_entry() for example). I need to use QR generation and attach them to the notification, and these codes are generated when the form is submitted.
CSV file has at least 3 columns: email, full_name and phone_number. Here's my code:
function generateData($filename, $date, $id){
$rows = array_map('str_getcsv', file($filename));
$header = array_shift($rows);
$csv = array();
foreach($rows as $row) {
$csv[] = array_combine($header, $row);
}
$count_array = count($csv);
for ($i=0; $i < $count_array; $i++) {
foreach ($csv[$i] as $key => $value) {
// delete rows that we don't need
if ($key != 'email' && $key != 'full_name' && $key != 'phone_number') {
unset($csv[$i][$key]);
}
}
}
insertGFAPI($csv);
}
function insertGFAPI($entries){
$count_entries = count($entries);
for ($i=0; $i < $count_entries; $i++) {
$data[$i]['input_1'] = $entries[$i]['email'];
$data[$i]['input_2'] = $entries[$i]['full_name'];
$data[$i]['input_3'] = $entries[$i]['phone_number'];
$result = GFAPI::submit_form( get_option('form-id'), $data[$i]);
}
The outcome that I'd like to get is pretty simple - I want to know why and how is it possible that submit_form() merges data from other loops and how I can prevent it.
Do you know what can I do with that?
Solved. It was necessary to empty $_POST array.
I'm trying to make an agenda of panelists for an event company - their site is made with PHP. They already have a CSV file which lists the panelist. I wrote some code so that they can just upload their CSV to their server and have it render as an table.
The csv is set up more or less like this:
Panel, Name, Last Name, Title, Company, Moderator
tuesday, John, Doe, Partner, Acme,1
tuesday, Jane, "O Reily", Partner, SkyNet,0
tuesday, Samatha, Klein, CEO, Sea World,0
tuesday, Bill, Clarke, Head of Marketing, TNT,0
wednesday, Mohammed, Algarisi, Managing Director, Cheesy Photos,1
wednesday, Tim, Draper, Founding and Managing Partner, Draper Associates,0
Anyhow, they want the panelists to be sorted alphabetically by last name, with the moderator displaying first. I'm having trouble doing this in PHP.
I'm not so used to PHP code so I'm sure I must be missing stuff, should I have set this up differently? What's the best way to sort it?
Here's basically what I did-
First I made a Panelist class:
class Panelist {
function __construct($panel, $name, $lastname, $title, $company, $moderator){
$this -> panel = $panel;
$this -> name = $name;
$this -> lastname = $lastname;
$this -> title = $title;
$this -> company = $company;
$this -> moderator = $moderator;
}
}
Then an empty array where we will store our Panelist objects
$panelists =array();
$row = 1;
//accesses our csv file from which we will get the data for the objects
if(($handle = fopen("agenda.csv", "r")) !== FALSE) {
//loops through the csv file by row
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
//skips the header (first) row
if($row == 1) {$row++; continue;}
//instanciates a Panelist object for every row in the csv file
$name = new Panelist($data[0], $data[1], $data[2], $data[3], $data[4], data[5] );
//adds object to our $panelist array
array_push($panelists, $name);
}
Then I have an output function that recieves two arguments:
1. $arr - the array where the objects are stored
2. $panelName - the name of the panel to output
function outputSpeakers($arr, $panelName){
// loops through objects in $arr
foreach($arr as $obj){
//only outputs objects with a panel value matching $panelName:
if($obj->panel == $panelName){
$name = $obj->name;
$lastname = $obj->lastname;
$title = $obj->title;
$company= $obj->company;
//lots of condition formatting stuff here that's not important such as...
if($obj->moderator == '1'){
//if the moderator is "TBA" - don't output title or company:
if($name == ' TBA'){
//format this way
} //else ...
}
}
}
}
?>
Then, in my agenda.php file I include the above class file and do:
<div class="panel-list">
<? outputSpeakers($panelist, "tuesday"); ?>
</div>
Thanks! :-)
You are getting there.
In brief, you can try this:
if ($obj->panel == $panelName) {
$result[$obj->{'last name'}] = $obj;
}
ksort($result);
But I would use a different way to create the agenda object.
<?php
class Panelist {
private $_agenda = null;
public function put($csv) {
if (!file_exists($csv)) {
return false;
}
if (($handle = fopen($csv, "r")) !== FALSE) {
$row = 1;
$count = 0;
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
if ($row == 1) {
$label = $data;
$count = count($data);
} else {
if (count($data) == $count) {
for($i = 0; $i < $count; $i++) {
$agenda[$row][trim(strtolower($label[$i]))] = trim(strtolower($data[$i]));
}
}
}
$row++;
}
fclose($handle);
$this->_agenda = json_decode(json_encode($agenda));
return $this;
}
}
public function get($label, $value) {
$result = [];
if (!property_exists($this, '_agenda')) {
return false;
}
foreach ($this->_agenda as $item) {
// loop through agenda for match values by label
if (!empty($item->{$label}) && !empty($item->{'last name'}) && $item->{$label} == $value) {
// arrange $result key with last name;
$result[$item->{'last name'}] = $item;
}
}
// sort $result by key with ascending order
ksort($result);
return $result;
}
}
$panelist = new Panelist;
if ($agenda = $panelist->put("agenda.csv")->get('panel', 'tuesday')) {
foreach ($agenda as $item) {
echo $item->name . '<br>';
}
}
OUTPUT:
bill
john
samatha
jane
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?
Having checked a variety of questions but not being able to find quite what I need, I am at a bit of a loss.
I am trying to chose the columns from MySQL I want exported to CSV by parsing the column names and adding the valid column names to a $colnames array, then adding those values as headers to the CSV and then only displaying the relevant data from the database through a while loop.
I have looked at the following in particular having been guided there from other questions: How to get all the key in multi-dimensional array in php
Here is the code:
function query_to_csv($query, $filename, $attachment = false, $headers = true, $specs_off = false) {
if($attachment) {
// send response headers to the browser
header( 'Content-Type: text/csv; charset=UTF-8' );
header( 'Content-Disposition: attachment;filename='.$filename);
$fp = fopen('php://output', 'w');
} else {
$fp = fopen($filename, 'w');
}
$result = mysql_query($query) or die( mysql_error() );
if($headers) {
// output header row (if at least one row exists)
$row = mysql_fetch_assoc($result);
if($row) {
// PRODUCTS TABLE SPECIFIC - get rid of specs_ and free_ columns so have nicer data set for user
if($specs_off) {
$columnames = array_keys($row);
$colnames = array();
//$colnames = array_keys($row);
foreach($columnames as $key => $value) {
if((substr_count($value, "spec_") < 1) && (substr_count($value, "free_") < 1)) {
array_push($colnames, $value);
}
}
}
else {
$colnames = array_keys($row);
}
// add in additional columns if exporting client data
if($table == 'clients') {array_push($colnames, "products", "last_order_date");}
//write the colnames to the csv file
fputcsv($fp, $colnames);
// reset pointer back to beginning
mysql_data_seek($result, 0);
}
} // done with the headers etc, now lets get on with the data
// clear out and create the $row_data array
$row_data = array();
// run through the row array adding values to row_data as we go
while($row = mysql_fetch_assoc($result)) {
// create the array_keys_multi from https://stackoverflow.com/questions/11234852/how-to-get-all-the-key-in-multi-dimensional-array-in-php/11234924#11234924
function array_keys_multi(array $array) {
$keys = array();
foreach ($array as $key => $value) {
$keys[] = $key;
if (is_array($array[$key])) {
$keys = array_merge($keys, array_keys_multi($array[$key]));
}
}
return $keys;
}
// run the function on the $row array
array_keys_multi($row);
// now use the $keys array
foreach($keys as $key => $value) {
// check if the value is in the colnames array and if so push the data on to the $row_data array ready for export to CSV
if(in_array($value, $colnames)) {
array_push($row_data, $row[$value]);
}
}
// now we are ready to write the CSV
fputcsv($fp, $row_data);
}
fclose($fp);
exit;
} // end of query_to_csv
// Write the sql statement
$sql = "SELECT * FROM ".$table." ";
if(isset($where_1_col)) { $sql .= " WHERE `".$where_1_col."` = '".$where_1_val."'"; }
if(isset($where_2_col)) { $sql .= " AND `".$where_2_col."` = '".$where_2_val."'"; }
if(isset($where_3_col)) { $sql .= " AND `".$where_3_col."` = '".$where_3_val."'"; }
if(isset($where_4_col)) { $sql .= " AND `".$where_4_col."` = '".$where_4_val."'"; }
if(isset($order_by_col)) { $sql .= " ORDER BY `".$order_by_col."` ". strtoupper($order_by_dir) ." "; }
// output as an attachment
query_to_csv($sql, $table."_export.csv", true, true, true);
All I am getting is a huge export of the chosen column names repeated as many times as there are values from the initial query. I don't know how to get the values in.
Any suggestions on where I am going wrong or how I can undertake this more neatly are welcomed.
It seems that you just append the new row data to $row_data but never clear that array.
array_push($row_data, $row[$value]);
What I did to fix it:
Move
// clear out and create the $row_data array
$row_data = array();
into the while loop.
Change
// clear out and create the $row_data array
$row_data = array();
while($row = mysql_fetch_assoc($result)) {
...
}
To
while($row = mysql_fetch_assoc($result)) {
// clear out and create the $row_data array
$row_data = array();
...
}
Note:
You are using $table everywhere but never define it. Like here if($table == 'clients')
If it is a global var you need to add global $table or a parameter to your function, too.
Edit:
As mentioned in my comment on your question you could just use array_keys() to get the keys.
php.net/manual/de/function.array-keys.php
And then change
array_keys_multi($row);
to
$keys = array_keys($row);
After that you can remove array_keys_multi()
Further you could move that part in front of your while-loop because you only need to calculate the column names you need once and not in every iteration.