php arrays to CSV - php

I have an array of arrays
$numbers= array(3) {
[months]=>
array(3) {
["1"]=>
string(7) "Jan"
["2"]=>
string(7) "Feb"
["3"]=>
string(7) "Mar"
}
[dates]=>
array(3) {
["1"]=>
string(7) "12th"
["2"]=>
string(7) "19th"
["3"]=>
string(7) "22nd"
}
[people]=>
array(3) {
["1"]=>
string(7) "Bill"
["2"]=>
string(7) "Ted"
["3"]=>
string(7) "Gary"
}
}
I want to write the contents of these arrays into a CSV file in the form of a table
so I get an output like:
months, dates, people
Jan, 12th, Bill
Feb, 19th, Ted
Mar, 22nd, Gary
I want to try and put it directly from the array into the CSV in one move it it's possible but I can't find a way to do it without cutting it up.

<?php
// transform the array
$keys = array_keys($numbers);
array_unshift($numbers, null);
$output = call_user_func_array('array_map', $numbers);
array_unshift($output, $keys);
// from php.net
$fp = fopen('file.csv', 'w');
foreach ($output as $fields) {
fputcsv($fp, $fields);
}
fclose($fp);

$mi = new MultipleIterator();
$headers = array();
foreach($numbers as $header => $data) {
$mi->attachIterator(new ArrayIterator($data));
$headers[] = $header;
}
$fh = fopen('myfile.csv', 'w');
fputcsv($fh, $headers);
foreach($mi as $values) {
fputcsv($fh, $values);
}
fclose($fh);

Related

Reading from a file into an associative array

I have to create a page, where the user is able to search a suburb and the page will print the postcode of that suburb.
I am having a little difficulty with putting the data from the .txt document into the variables for the associative array.
Thanks for your help.
This is what I have so far.
<?php
$file = "postcode.txt";
$handle = fopen($file, 'r');
$postcodearray = file($file);
$suburb = explode(",", );
$postcodearray[$suburb] = $postcode;
fclose($handle)
?>
and this is the format of the .txt document...
3000,MELBOURNE
3001,MELBOURNE
3002,EAST MELBOURNE
3003,WEST MELBOURNE
etc.
$postcodearray = file($file);
foreach($postcodearray as $pca){
$p_codes=explode(',',$pca);
$postcodearray2[$p_codes[1]] = $p_codes[0];
}
print_r($postcodearray2);
I prefer file_get_contents when working with files
<?php
$content = file_get_contents('postcode.txt');
$rows = explode("\n", $content);
$data = [];
foreach ($rows as $row) {
$columns = explode(',', $row);
$data[$columns[0]] = $columns[1];
}
An alternative array would group MELBOURNE EAST and WEST in one array with subarrays. (Look at the output, I don't know how to explain it)
I explode MELBOURNE EAST on space and use EAST as a key in the array.
// Replace this line with file_get_contents("postcode.txt");
$txt = "3000,MELBOURNE
3001,MELBOURNE
3002,EAST MELBOURNE
3003,WEST MELBOURNE
3603,WEST SYDNEY
3103,NORTH PERTH";
$rows = explode(PHP_EOL, $txt);
$arr= [];
foreach($rows as $row){
List($postcode, $suburb) = explode(",", $row);
If(in_array(substr($suburb,0,4), array("EAST", "WEST")) || in_array(substr($suburb,0,5), array("SOUTH", "NORTH"))){
// If the suburb includes a direction explode it to temp.
$temp = explode(" ", $suburb);
$arr[$temp[1]][$temp[0]][] = $postcode;
}else{
// If there is no direction just save it as suburb "main"
$arr[$suburb][] = $postcode;
}
}
Var_dump($arr);
https://3v4l.org/RXgSR
Output:
array(3) {
["MELBOURNE"]=>
array(4) {
[0]=>
string(4) "3000"
[1]=>
string(4) "3001"
["EAST"]=>
array(1) {
[0]=>
string(4) "3002"
}
["WEST"]=>
array(1) {
[0]=>
string(4) "3003"
}
}
["SYDNEY"]=>
array(1) {
["WEST"]=>
array(1) {
[0]=>
string(4) "3603"
}
}
["PERTH"]=>
array(1) {
["NORTH"]=>
array(1) {
[0]=>
string(4) "3103"
}
}
}

PHP Export to CSV is putting all in 1 column

First a disclaimer, I am a noob here. I am trying to output my results into an excel file, however for some reason I can't seem to figure it, all the results are entering into the same column
Here is the function that I am using to convert it to the file:
function createCSVFile($filename,$headings,$data) {
// Set Output Headers
header('Content-Type: text/csv; charset=utf-8');
header("Content-Disposition: attachment; filename={$filename}.csv");
$fp = fopen('php://output', 'w');
$head = array();
foreach ($headings as $heading) {
$head[] = $heading;
}
fputcsv($fp, $head);
$rowData = array();
// Put the data into the csv
foreach ($data as $row) {
foreach ($row as $item) {
$rowData[] = $item;
}
fputcsv($fp, $rowData);
unset($rowData);
}
}
Here is some sample data and the structure of what I am passing:
$filename
$filename = "Staff-list";
$headings
$headings = array("Username","First Name","Last Name","Start Date", "End Date");
$data
$data = getStaffDetails();
Which returns:
array(6) {
[0]=>
array(5) {
[0]=>
string(12) "James21"
[1]=>
string(3) "James"
[2]=>
string(9) "Michael"
[3]=>
string(10) "2016-06-01"
[4]=>
string(10) "0000-00-00"
}
[1]=>
array(5) {
[0]=>
string(14) "thombommom"
[1]=>
string(5) "Thomas"
[2]=>
string(7) "Bomarius"
[3]=>
string(10) "2016-12-01"
[4]=>
string(10) "0000-00-00"
}
}
And here is what it looks like in the ouput:
Update 1:
As per Marks solution below, I tried setting the deliminator in the PHP func to ; like so:
fputcsv($fp, $head,';');
However, now the output just has semi colons instead of commas
One of the reasons I hate windows so much is that with every version, something is different making it harder for devs. Argh.... Anyway, what you need to do is override system setting ("list separator character") with: 'sep=;'.
The first thing you should pass to fputcsv is:
$seperator = "sep=;";
fputcsv($fp, $seperator, ';', ' ');
Then Make your data an array of arrays with the first array being your headings like so:
$data = array(array("One","Two", "Three"), array('1','2','3'),array('1','2','3'),array('1','2','3'));
Just because you said you're a noob I'll give ya the whole function:
function createCSVFile($filename,$data) {
// Set Output Headers
header('Content-Type: text/csv; charset=utf-8');
header("Content-Disposition: attachment; filename={$filename}.csv");
$fp = fopen('php://output', 'w');
// This will override system setting ("list separator character") and Excel will open the file correctly.
$seperator = "sep=;";
fputcsv($fp, $seperator, ';', ' ');
// Get the array initialised.
$rowData = array();
// put the data into the csv
foreach ($data as $row) {
foreach ($row as $item) {
$rowData[] = $item;
}
fputcsv($fp, $rowData);
unset($rowData);
}
}
Keep me posted!

build json data from php object

I want to buld a Json object to feed my graphs. I have got the following code to change my PHP object.
$rows = $this->Website_model->getGraphData();
$_rows = array();
$i = 0;
foreach ($rows as $key => $row) {
foreach ($row as $column => $value) {
$_rows[$i][] = $value;
}
$i++;
}
$rows = $_rows;
echo json_encode(array("sEcho" => intval($sEcho), "data" => $rows));
die();
My current ouput looks like this:
array(24) {
[0]=>
array(3) {
[0]=>
string(7) "3283581"
[1]=>
string(10) "2013-10-16"
}
It should look something like this:
{"y":15,"x":"2012-11-19"},{"y":18,"x":"2012-11-19"} etc etc
How can I add the Y and X to my data and take care i will get the right output to feed my graph?
/////////////////////////////////////////////////////
I tried the following:
Now i'm using the following code:
$rows = $this->Website_model->getGraphDataPositives();
$_rows = array();
$i = 0;
foreach ($rows as $key => $row) {
foreach ($row as $column => $value) {
$_rows[$i]['x'] = $value;
$_rows[$i]['y'] = $value;
$i++;
}
}
This results in the following response:
array(48) {
[0]=>
array(2) {
["x"]=>
string(7) "3283581"
["y"]=>
string(7) "3283581"
}
[1]=>
array(2) {
["x"]=>
string(10) "2013-10-16"
["y"]=>
string(10) "2013-10-16"
}
So it isn't okay yet.. it should say:
array(48) {
[0]=>
array(2) {
["x"]=>
string(7) "3283581"
["y"]=>
string(7) "2013-10-16"
}
[1]=>
array(2) {
["x"]=>
string(10) "1512116"
["y"]=>
string(10) "2013-10-17"
}
This would create an array like you wish :
$rows = $this->Website_model->getGraphData();
$_rows = array();
$i = 0;
foreach ($rows as $key => $row) {
$_rows[$i]['y'] = $rows[0];
$_rows[$i]['x'] = $rows[1];
$i++;
}
Your example data is not correct. You have array(3), but you show only 2 elements. Also in the output data you have 3283581 and the y values are 15 and 18. So there is no way I can guess how to convert those values.

Create subset of php array and convert to json

This is one of those that should be easy. I'm not even sure if "subset" is the right way to describe it.
My initial array looks like this:
array(3) { [0]=> array(5) { ["id"]=> string(1) "1" ["claim_id"]=> string(1) "1" ["price"]=> string(2) "50" ["date"]=> string(19) "2013-05-15 01:58:48" ["created"]=> string(19) "2013-05-15 01:58:48" } [1]=> array(5) { ["id"]=> string(2) "11" ["claim_id"]=> string(1) "1" ["price"]=> string(2) "45" ["date"]=> string(19) "2013-05-15 03:34:59" ["created"]=> string(19) "2013-05-15 03:37:01" } [2]=> array(5) { ["id"]=> string(2) "25" ["claim_id"]=> string(1) "1" ["price"]=> string(2) "50" ["date"]=> string(19) "2013-05-15 22:47:46" ["created"]=> string(19) "2013-05-15 22:52:02" } }
I'd ultimately like to end up with just the date and price values, swap them so that date is first in the array, reformat the date, and convert it to a json array that looks something like this:
[{"date":"Mar. 15","price":"50"},{"date":"Mar. 15","price":"45"},{"date":"Mar. 15","price":"50"}]
I ran a foreach statement to get at the data and reformat the date, then went out of my league with splice, unset, and other functions that took me in the wrong direction. Any ideas?
Try this
$array = array();
for($i = 0 ; $i<count($your_array);$i++) {
$a=array();
$a['date'] = $your_array[$i]['date'];
$a['price'] = date("F .j",strtotime($your_array[$i]["date"]));
array_push($array,$a);
}
json_encode($array);
Output
[{"date":"Mar. 15","price":"50"},{"date":"Mar. 15","price":"45"},{"date":"Mar. 15","price":"50"}]
Codepad
This should get you there
$ret = array();
foreach ($source as $rec){
$ret[] = array("date"=>$rec["date"], "price"=>$rec["price"]);
}
$json = json_encode($ret);
Create a quick function to create another array with only selected elements:
function datePriceToJson($array) {
$a = array();
foreach($array as $i => $a) {
$a[] = array("date" => $a['date'], "price" => $a['price']); //Creae a new array based on the one you want
}
return json_encode($a);
}
datePriceToJson($array);
You need to reconstruct array using correct foreach and the use json_encode to get the json
$req_array = array();
foreach($youArray as $value)
{
$temp = array();
$temp['date'] = $value['date'];
$temp['price'] = $value['price'];
$req_array[] = $temp;
}
$json = json_encode($req_array);
echo $json;
see demo
Hope it helps you
$infos =array(
array("id" =>"1","price"=>"50","date"=>"2013-05-15 01:58:48"),
array("id" =>"2","price"=>"55","date"=>"2013-06-15 01:58:48")
);
$i=0;
foreach ($infos as $info )
{
$infos[$i]["date"]= date("F .j",strtotime($info["date"]));
$i++;
}
echo json_encode($infos);

PHP Error: Undefined offset error within foreach loop

I have a csv file which I am trying to turn into a different structured array. First, I turn it into an array named all_data() constructed like this:
$data = file_get_contents($id . '.csv');
$data_array = explode("\n", $data);
foreach($data_array AS $data){
$all_data[] = explode("\t", $data);
}
results look like this:
array(5) {
[0]=>
array(2) {
[0]=>
string(10) "2012-11-14"
[1]=>
string(2) "10"
}
[1]=>
array(2) {
[0]=>
string(10) "2012-11-14"
[1]=>
string(2) "10"
}
[2]=>
array(2) {
[0]=>
string(10) "2012-11-14"
[1]=>
string(2) "10"
}
[3]=>
array(2) {
[0]=>
string(10) "2012-11-14"
[1]=>
string(2) "10"
}
[4]=>
array(1) {
[0]=>
string(0) ""
}
}
And then I turn it into im_arr() with the following code:
foreach($all_data as $key => $value){
$im_arr[$key][$value[0]] = $value[1];
}
The results:
array(5) {
[0]=>
array(1) {
["2012-11-14"]=>
string(2) "10"
}
[1]=>
array(1) {
["2012-11-14"]=>
string(2) "10"
}
[2]=>
array(1) {
["2012-11-14"]=>
string(2) "10"
}
[3]=>
array(1) {
["2012-11-14"]=>
string(2) "10"
}
[4]=>
array(1) {
[""]=>
NULL
}
}
And then, finally another foreach loop gives me the results I am looking for:
foreach ($im_arr as $val) {
foreach ($val as $key => $val2) {
$im_data[$key]=$val2;
}
}
With the result for im_data() being:
array(2) {
["2012-11-14"]=>
string(2) "10"
[""]=>
NULL
}
Which would be perfect, since the array im_data() is exactly what I would like to get out of all_data(). However, when I am trying to put this code in another part of the program it doesn't work, and I am thinking it might be because of the warnings I receive:
"PHP Notice: Undefined offset: 1 in ... on line 93"
Line 93 corresponds to this line:
$im_arr[$key][$value[0]] = $value[1];
Here is the complete part of the code:
$all_data = array();
$im_arr=array();
$data = file_get_contents($id . '.csv');
$data_array = explode("\n", $data);
foreach($data_array AS $data){
$all_data[] = explode("\t", $data);
}
foreach($all_data as $key => $value){
$im_arr[$key][$value[0]] = $value[1]; //the line for the error
}
$im_data=array();
foreach ($im_arr as $val) {
foreach ($val as $key => $val2) {
$im_data[$key]=$val2;
}
}
var_dump($im_data);
I know there are many many questions posted for this same error, but I couldn't figure out the problem with this particular piece of code.
This is the problem:
[4]=>
array(1) {
[0]=>
string(0) ""
}
Just check that the data is set, and isn't empty before adding them to $im_arr:
foreach ($all_data as $key => $value) {
if (isset($value[0]) && isset($value[1]) && !empty($value[0]) && !empty($value[1])) {
$im_arr[$key][$value[0]] = $value[1];
}
}
For every foreach i would pre-check if the first argument is an array
For instance ;
//Just add line below for every foreach (and add any required else statement if needed)
if(is_array($im_arr))
foreach ($im_arr as $val) {
if(is_array($val))
foreach ($val as $key => $val2) {
$im_data[$key]=$val2;
}
}

Categories