I want to make a array out of a csv file with the header as key. But when I insert the script into a database than it overrides the previous row of the csv file and only the last value gets stored in the database.
I think its because the array has a default value of 5. How can I change the value so that it creates a new value?
This is the script
<?php
// open the file.
if (($handle = fopen("test2.csv", "r")) !== FALSE) {
// read the column headers in an array.
$head = fgetcsv($handle, 1000, ";");
// read the actual data.
while (($data = fgetcsv($handle, 1000, ";")) !== FALSE) {
// create a new array with the elements in $head as keys
// and elements in array $data as values.
$combined = array_combine($head,$data);
// print.
var_dump($combined);
}
// done using the file..close it,
}
?>
this is the output
array(5) { ["name"]=> string(5) "Harry" ["description"]=> string(4) "test" ["offer_url"]=> string(42) "demo.com/admin/offers/add" ["preview_url"]=> string(42) "demo.com/admin/offers/add" ["expiration_date"]=> string(9) "23-8-2013" }
array(5) { ["name"]=> string(5) "Gerry" ["description"]=> string(4) "test" ["offer_url"]=> string(42) "demo.com/admin/offers/add" ["preview_url"]=> string(42) "demo.com/admin/offers/add" ["expiration_date"]=> string(9) "23-8-2013" }
array(5) { ["name"]=> string(5) "merry" ["description"]=> string(4) "test" ["offer_url"]=> string(42) "demo.com/admin/offers/add" ["preview_url"]=> string(42) "demo.com/admin/offers/add" ["expiration_date"]=> string(9) "23-8-2013" }
you must go through multidimensional array and add additional index to the combined param like this - combined[]=...:
// create a new array with the elements in $head as keys
// and elements in array $data as values.
$combined[] = array_combine($head,$data);
Related
I have this array, and I want to convert it into a CSV file, the problem, is that the array does not generate a csv properly, but just empty fields, why?
Here's my array contents (the array that I'm printing here is $listaParaCSV, as the code shown below):
array(2) {
[0]=>
array(22) {
[0]=> string(6) "nombre"
[1]=> string(14) "Lun 11-01-2021"
[2]=> string(14) "Mie 13-01-2021"
[3]=> string(14) "Lun 18-01-2021"
[4]=> string(14) "Mie 20-01-2021"
[5]=> string(14) "Lun 25-01-2021"
}
[1]=>
array(85) {
["Pedro"]=>
array(21) {
["Lun 11-01-2021"]=> string(2) "SI"
["Mie 13-01-2021"]=> string(2) "SI"
["Lun 18-01-2021"]=> string(2) "SI"
["Mie 20-01-2021"]=> string(0) ""
["Lun 25-01-2021"]=> string(0) ""
}
["Maria"]=>
array(21) {
["Lun 11-01-2021"]=> string(2) "SI"
["Mie 13-01-2021"]=> string(2) "SI"
["Lun 18-01-2021"]=> string(0) ""
["Mie 20-01-2021"]=> string(0) ""
["Lun 25-01-2021"]=> string(0) ""
}
}
}
And here is my code (the variables $listaFechas and $paraCSV are arrays themselves):
$listaParaCSV = array (
$listaFechas,
$paraCSV
);
$fp = fopen('backupAsistenciaCurso-'.$cursoID.'.csv', 'w');
foreach ($listaParaCSV as $fields) {
fputcsv($fp, $fields);
}
fclose($fp);
The expected result is a CSV file that when opened with open with OpenCalc or excel shows something like this:
The problem is that you are looping over the $listaParaCSV with has 2 elements, the headers and then all the data in one element.
Instead, if you write out the headers and then loop over $paraCSV, adding the key (the name) as the first field before outputting them...
$fp = fopen('backupAsistenciaCurso-'.$cursoID.'.csv', 'w');
fputcsv($fp, $listaFechas);
foreach ($paraCSV as $key => $fields) {
array_unshift($fields, $key);
fputcsv($fp, $fields);
}
I have a series of arrays, like similar:
$my_array = {"foo"=>"bar", "sudo"=>"make_sandwhich", "bam"=>"bang"};
and a csv like:
Header 1, Header 2, foo, Header 4 , bam , Header 5
Lorem. , Ipsum. , , cheesecake, Henrietta, Loreal
, , , , , New Hampshire
And I want the csv to look like this when I add the example line from the start...
Header 1, Header 2, foo, Header 4 , bam , Header 5 , sudo
Lorem. , Ipsum. , , cheesecake, Henrietta, Loreal ,
, , , , , New Hampshire,
, , bar, , bang , , make_sandwhich
I've tried messing with the fputcsv, but it doesn't seem to have anything near the functionality I need. Is there a way to do this?
It can be achieved with fgetcsv and fputcsv and "some" additional processing.
Read your csv file (first row are the headers), then add the new headers from your input row.
Then read the rows, create missing data for new headers and add a new row with all the headers at the end.
Then just write that data back to csv file.
a.csv - input:
Header 1, Header 2, foo, Header 4 , bam , Header 5
Lorem. , Ipsum. , , cheesecake, Henrietta, Loreal
, , , , , New Hampshire
code:
<?php
$myArray = ["foo"=>"bar", "sudo"=>"make_sandwhich", "bam"=>"bang"];
$readHandle = fopen("a.csv", "r");
// get headers (first row)
$headers = fgetcsv($readHandle);
$allHeaders = [];
foreach ($headers as $header) {
$allHeaders[] = trim($header);
}
// add missing headers from the input data (so to headers from file add sudo header)
foreach (array_keys($myArray) as $data) {
if (!in_array($data, $allHeaders)) {
$allHeaders[] = $data;
}
}
var_dump($allHeaders);
// read all rows from the file and add the new headers
$rows = [];
while($row = fgetcsv($readHandle)) {
foreach ($allHeaders as $k => $header) {
$row[$k] = isset($row[$k]) ? trim($row[$k]) : '';
}
$rows[] = $row;
}
// add the new row from input data
$newRow = [];
foreach ($allHeaders as $header) {
$newRow[] = $myArray[$header] ?? '';
}
$rows[] = $newRow;
var_dump($rows);
fclose($readHandle);
// now write headers and rows to csv file
$writeHandle = fopen('b.csv', 'w+');
fputcsv($writeHandle, $allHeaders);
foreach ($rows as $row) {
fputcsv($writeHandle, $row);
}
fclose($writeHandle);
$allHeaders:
array(7) {
[0]=>
string(8) "Header 1"
[1]=>
string(8) "Header 2"
[2]=>
string(3) "foo"
[3]=>
string(8) "Header 4"
[4]=>
string(3) "bam"
[5]=>
string(8) "Header 5"
[6]=>
string(4) "sudo"
}
$rows:
array(3) {
[0]=>
array(7) {
[0]=>
string(6) "Lorem."
[1]=>
string(6) "Ipsum."
[2]=>
string(0) ""
[3]=>
string(10) "cheesecake"
[4]=>
string(9) "Henrietta"
[5]=>
string(6) "Loreal"
[6]=>
string(0) ""
}
[1]=>
array(7) {
[0]=>
string(0) ""
[1]=>
string(0) ""
[2]=>
string(0) ""
[3]=>
string(0) ""
[4]=>
string(0) ""
[5]=>
string(13) "New Hampshire"
[6]=>
string(0) ""
}
[2]=>
array(7) {
[0]=>
string(0) ""
[1]=>
string(0) ""
[2]=>
string(3) "bar"
[3]=>
string(0) ""
[4]=>
string(4) "bang"
[5]=>
string(0) ""
[6]=>
string(14) "make_sandwhich"
}
}
b.csv - output:
"Header 1","Header 2",foo,"Header 4",bam,"Header 5",sudo
Lorem.,Ipsum.,,cheesecake,Henrietta,Loreal,
,,,,,"New Hampshire",
,,bar,,bang,,make_sandwhich
I hope you dont want the spaces in csv for formatting. It can also be done but you need to keep the amount of characters for the longest string in each column and pad the values to that lengths.
I'm trying to unset a couple items from an array at once, send unsetted items to another array.
array(6) {
[0]=> string(65) "https://www.kintetsu-re.co.jp/mansion_kansai/outline/midosuji241/"
[1]=> string(41) "https://geo.8984.jp/outline/suminodo.html"
[2]=> string(56) "http://www.sohgoh-outline.jp/index.php?bunjo_number=0141"
[3]=> string(56) "http://www.sohgoh-outline.jp/index.php?bunjo_number=0136"
[4]=> string(56) "http://www.sohgoh-outline.jp/index.php?bunjo_number=0099"
[5]=> string(53) "https://www.sgr-sumai.jp/mansion/tezukayama21/outline"
}
Three links in this array starts with http://www.sohgoh-outline.jp . So I'm trying to unset those. But not one by one. I can already doing it. For example, I tried to locate those with strpos
$needle = "http://www.sohgoh-outline.jp/";
foreach ($link as $unset){
if (($index = strpos($unset, $needle)) !== false){
$renai [] = $unset[$index];
unset($unset[$index]);
}
}
But this error popping up.
Cannot unset string offsets
Any suggestions?
change your code like this:
foreach ($link as $k => $unset){
if ((strpos($unset, $needle)) !== false)
{
$renai [] = $link[$k]; // This will add the value to new array.
unset($link[$k]); // THIS WILL UNSET THE VALUE.
}
}
The simplest method is probably regex with preg_grep and array_diff.
$out = preg_grep("/.*?(sohgoh-outline\.jp).*/", $arr);
var_dump($out); //sohgoh-outline.jp links
$arr = array_diff($arr, $out);
var_dump($arr); // all but sohgoh-outline.jp links
Output of above code:
array(3) {
[2]=>
string(56) "http://www.sohgoh-outline.jp/index.php?bunjo_number=0141"
[3]=>
string(56) "http://www.sohgoh-outline.jp/index.php?bunjo_number=0136"
[4]=>
string(56) "http://www.sohgoh-outline.jp/index.php?bunjo_number=0099"
}
array(3) {
[0]=>
string(65) "https://www.kintetsu-re.co.jp/mansion_kansai/outline/midosuji241/"
[1]=>
string(41) "https://geo.8984.jp/outline/suminodo.html"
[5]=>
string(53) "https://www.sgr-sumai.jp/mansion/tezukayama21/outline"
}
https://3v4l.org/Um46H
I'm trying to loop through some CSV data and take out the $data[4] item. My eventual goal is to find the average and hopefully use PHP's array_sum. This seems to be working, except that every time I try and create this array, my while loop breaks each value into their own separate arrays ($real), not one array that I can work with. I have tried everything, including working with the arrays outside of the loop, but nothing has worked. Any help would be appreciated!
$symbol=array("XOM","CVX","RDS-A",
"PTR","TOT","SNP","COP",
"IMO","BP","E","STO","EC","SU","MRO");
for($i=0; $i<count($symbol);$i++)
{
$handle = #fopen("http://ichart.yahoo.com/table.csv?s={$symbol[$i]}&a=10&b=12&c=2013&d=10&e=12&f=2013&g=d&ignore=.csv", "r", false, $context);
if ($handle === false)
{
// trigger (big, orange) error
trigger_error("Could not connect to Yahoo!", E_USER_ERROR);
exit;
}
// download title of CSV file and throw away
$data=fgetcsv($handle);
//loop through data
while(($data = fgetcsv($handle)) !==FALSE)
{
$rows++;
$num=count($data);
$real=array($data[4]);
}
var_dump($real);
}
And here's my final output:
array(1) { [0]=> string(9) "92.669998" }
array(1) { [0]=> string(6) "120.00" }
array(1) { [0]=> string(9) "66.290001" }
array(1) { [0]=> string(10) "111.059998" }
array(1) { [0]=> string(5) "58.73" }
array(1) { [0]=> string(9) "82.449997" }
array(1) { [0]=> string(5) "72.82" }
array(1) { [0]=> string(9) "42.740002" }
array(1) { [0]=> string(5) "45.91" }
array(1) { [0]=> string(5) "47.98" }
array(1) { [0]=> string(9) "22.440001" }
array(1) { [0]=> string(5) "41.93" }
array(1) { [0]=> string(5) "34.82" }
array(1) { [0]=> string(5) "35.82" }
Not sure what $context is, but try this...
$symbol=array("XOM","CVX","RDS-A","PTR","TOT","SNP","COP","IMO","BP","E","STO","EC","SU","MRO");
$datas = array();
for($i=0; $i<count($symbol);$i++){
$handle = #fopen("http://ichart.yahoo.com/table.csv?s={$symbol[$i]}&a=10&b=12&c=2013&d=10&e=12&f=2013&g=d&ignore=.csv", "r", false, $context);
if ($handle === false){
// trigger (big, orange) error
trigger_error("Could not connect to Yahoo!", E_USER_ERROR);
exit;
}
// download title of CSV file and throw away
$data=fgetcsv($handle);
//loop through data
while(($data = fgetcsv($handle)) !==FALSE){
$rows++;
$datas[] = $data[4];
}
}
print_r($datas);
I am trying to upload csv file data using PHP,
CSV File Data (Semicolon separated)
Name;Nom;Tel;Email;Ville;ID
x;DURAND;11;aprasquier+testvia#odm-tech.com;"Paris";1
PHP Code:
$handle = fopen('test.csv', "r");
while (($data = fgetcsv($handle,0, ";")) !== FALSE)
echo var_dump($data);
output:
array(1) {
[0]=> string(53) "x;DURAND;11;aprasquier+testvia#odm-tech.com;"Paris";1"
}
Expected output is ,
array(6) {
[0]=> string(1) "x"
[1]=> string(6) "DURAND"
[2]=> string(2) "11"
[3]=> string(31) "aprasquier+testvia#odm-tech.com"
[4]=> string(5) "Paris"
[5]=> string(1) "1"
}
Please anyone advise on this asap.