Use array for array push instead of a string - php

I'm using the following code:
$patients_with_site = [];
if (in_array($zip_code, $current_zip_codes)) {
echo "The referral id is: ".$referral_id;
array_push($patients_with_site,$referral_id);
print_r($patients_with_site);
}
I'm then trying to push it to a CSV file with this code:
$fp = fopen('patients_with_site.csv', 'w');
foreach ($patients_with_site as $fields) {
fputcsv($fp, $fields);
}
fclose($fp);
I'm getting an error saying that the $patients_with_site is a string and fputcsv requires an array.

If fputcsv requires array - provide array:
foreach ($patients_with_site as $fields) {
fputcsv($fp, [$fields]);
}
And yes, every value of $patients_with_site is a string and not array.

Your $patients_with_site's elements are strings.
The second argument of fputcsv must be an array, so unless you have a multidimensional array for $patients_with_site you shouldn't loop through it.
So it should work if you only call fputcsv($fp, $patients_with_site).
See PHP fputcsv

Related

Need two dimensional array for 2 column CSV from 2 strings

I am working on a project to create 2 column CSV using PHP and i have the data stored as strings in 2 different variables . Consider below example of what i have and what i need further. Thank you in advance.
I have below 2 variables and data stored inside them. (data is separated by comma)
$title = title1,title2,title3,title4,title5..and so on
$values = value1,value2,value3,value4,value5..and so on
I need this array pattern like this
$multi_array = array
(
array(title1,value1),
array(title2,value2),
array(title3,value3),
);
I will then use the below code to generate 2 column CSV via PHP
// open the file "demosaved.csv" for writing
$file = fopen('demosaved.csv', 'w');
// save the column headers
fputcsv($file, array('Column 1', 'Column 2'));
// save each row of the data
foreach ($multi_array as $row)
{
fputcsv($file, $row);
}
// Close the file
fclose($file);
Since the values are comma separated strings, explode them into arrays:
$title = explode(",", $title);
$values = explode(",", $values);
Then you can just use the key to match up the values from each array (assuming that they are the same length):
foreach ($values as $key => $val)
{
fputcsv($file, [$title[$key], $val]);
}
Or combine them:
$multi_array = array_combine($title, $value);
foreach ($multi_array as $title => $value)
{
fputcsv($file, [$title, $value]);
}
If you're on an old version of PHP you'll need array() instead of [ ].
From the OP, since there many be duplicates in the string that would be duplicate keys: "use the below code to perform the same job and even keep the duplicate keys. PHP array_combine removes the duplicate array entries but below code keeps all entries:"
$arrKeys = array('str', 'str', 'otherStr');
$arrVals = array('1.22', '1.99', '5.17');
function foo($key, $val) {
return array($key=>$val);
}
$arrResult = array_map('foo', $arrKeys, $arrVals);
print_r($arrResult);

PHP Array Only Returning One Result to CSV

I'm relatively new to PHP, so please excuse my ignorance if this is an easy one.
I am pulling in results from an API call with an end goal being that I write all results to a CSV file, I was able to get everything working, except for the fact that it only writes the first array to the CSV file. I know there are more records (arrays) because when I echo the results I typically get 10-15 results back. Below is my code that I'm using.
foreach ($list as $order) {
$listOrders = array (
array($order->getBuyerName(), $address['AddressLine1'], $address['AddressLine2'], $address['AddressLine3'], $address['City'], $address['StateOrRegion'], $address['PostalCode'], $orderinfo->getSKU())
);
}
$fp = fopen('order-file.csv', 'w');
foreach ($listOrders as $fields) {
fputcsv($fp, $fields);
}
fclose($fp);
Here is a sample of the one result, though there should be around 10-15:
"TONYA","7X XX Avenue",,,"Spokane Valley",WA,99212,B123
You always overwrite the $listOrders array with each foreach cycle. To add element to array, use $listOrders[] = $var syntax, so it should look something like this
$listOrders = array();
foreach ($list as $order) {
$listOrders[] = array($order->getBuyerName(), $address['AddressLine1'], $address['AddressLine2'], $address['AddressLine3'], $address['City'], $address['StateOrRegion'], $address['PostalCode'], $orderinfo->getSKU());
}

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
}
?>

Export mysql data in CSV in CakePHP

In CakePHP, with the following code i am trying to Export users email in CSV.
I am getting Errors.
Code Refrence site
Error:
Notice (8): Undefined offset: 0 [APP\View\Frontusers\admin_exportemails.ctp, line 12]
Warning (2): fputcsv() expects parameter 2 to be array, null given [APP\View\Helper\CsvHelper.php, line 36]
Notice (8): Undefined offset: 1 [APP\View\Frontusers\admin_exportemails.ctp, line 12]
Warning (2): fputcsv() expects parameter 2 to be array, null given [APP\View\Helper\CsvHelper.php, line 36]
admin_exportemails.ctp
$line= $useremails[0]['Frontuser'];
$this->CSV->addRow(array_keys($line));
foreach ($useremails as $key => $useremail)
{
$line =$useremail[$key]['Frontuser'];
$this->CSV->addRow($line);
}
$filename='useremails';
echo $this->CSV->render($filename);
You're messing up your foreach. You split it up in the $key and the $useremail sub-array, which is OK. But then you iterate over it and try to access $useremail[$key]['Frontuser'] again, which is nonexistent at that point.
foreach ($useremails as $key => $useremail)
This causes the [0] and [1] in the original $useremails array to be set as $key, but you iterate over all the items over the $useremails, so you can simply:
$line = $useremail['Frontuser'];
You don't need the $key, since that's not part of the iterated item, e.g. the first time your foreach runs, it sees this:
[Frontuser] => Array
(
[name] => Rash
[email] => rash.com
)
And on the second iteration it sees this:
[Frontuser] => Array
(
[name] => John
[email] => john#gmail.com
)
So there is no [0] or [1] index anymore.
$useremail[$key]['Frontuser'];
should be
$useremail['Frontuser'];
Actually there's no need for your code to include the key in the foreach loop at all.
That's PHP 101, so for further information please refer to the manual: http://php.net/foreach
You can simply pass your data array in that function and your csv generated in webroot folder.
Note:- 1. You should put blank csv file at webroot folder.
2. you should store all information in a sub array which contain only values not Model index.
function generate_csv($data_array=array()){
// pr($data_array);die;
foreach ($data_array as $key => $value) {
$newdata[] = $key.','.$value;
}
// pr($newdata);die;
$f = fopen(APP.'webroot/csv_file.csv', 'w+');
foreach ($newdata as $line) {
fputcsv($f, array($line), ',');
}
fseek($f, 0);
fclose($f);
}
you made mistake in the for loop and iterated it in wrong way.just ommit the below line from the foreach loop.
$line =$useremail[$key]['Frontuser'];
Here have tow options
1. save csv file in folder not sent output to browser and
2. send output to browser
function generate_csv($data_array = array()) {
//$f = fopen(APP . 'webroot/files/unsaved_bars.csv', 'w+'); // for save csv file in folder not sent output to browser
$f = fopen("php://output", "a"); // for send output to browser
$headers[] = array('id','name','other_info'); // for header row
$data_array = array_merge($headers, $data_array);
foreach ($data_array as $line) {
fputcsv($f, $line, ',');
}
//fseek($f, 0);
fclose($f);
}

How to read each field into an array properly?

I have this structure in a csv file
"http://example.com/example.jpg","example","example2","example3","1234,56"
Now I assign this line to a variable $line and
$fields = explode('","',$line);
It stops at "http". The same with
$fields = csv2array(str_replace(':','\\:',$line),$delimiter=',',$enclosure='"',$escape='\\');
where
function csv2array($input,$delimiter=',',$enclosure='"',$escape='\\'){
$fields=explode($enclosure.$delimiter.$enclosure,substr($input,1,-1));
foreach ($fields as $key=>$value)
$fields[$key]=str_replace($escape.$enclosure,$enclosure,$value);
return($fields);
}
How to read each field into an array?
I would suggest reading the file using fgetcsv() which returns an array of values exactly as you want.

Categories