-
Star
(265)
You must be signed in to star a gist -
Fork
(78)
You must be signed in to fork a gist
-
-
Save jaywilliams/385876 to your computer and use it in GitHub Desktop.
<?php | |
/** | |
* Convert a comma separated file into an associated array. | |
* The first row should contain the array keys. | |
* | |
* Example: | |
* | |
* @param string $filename Path to the CSV file | |
* @param string $delimiter The separator used in the file | |
* @return array | |
* @link http://gist.github.com/385876 | |
* @author Jay Williams <http://myd3.com/> | |
* @copyright Copyright (c) 2010, Jay Williams | |
* @license http://www.opensource.org/licenses/mit-license.php MIT License | |
*/ | |
function csv_to_array($filename='', $delimiter=',') | |
{ | |
if(!file_exists($filename) || !is_readable($filename)) | |
return FALSE; | |
$header = NULL; | |
$data = array(); | |
if (($handle = fopen($filename, 'r')) !== FALSE) | |
{ | |
while (($row = fgetcsv($handle, 1000, $delimiter)) !== FALSE) | |
{ | |
if(!$header) | |
$header = $row; | |
else | |
$data[] = array_combine($header, $row); | |
} | |
fclose($handle); | |
} | |
return $data; | |
} | |
/** | |
* Example | |
*/ | |
print_r(csv_to_array('example.csv')); | |
?> |
name | number | |
---|---|---|
Lorem | 11 | |
ipsum | 22 |
Array | |
( | |
[0] => Array | |
( | |
[name] => Lorem | |
[number] => 11 | |
) | |
[1] => Array | |
( | |
[name] => ipsum | |
[number] => 22 | |
) | |
) |
I just made an ugly tiny version for composer / packagist (remember left-pad for JS, yolo)
composer require rap2hpoutre/csv-to-associative-array
This is awesome! I used it for importing large amount of data into a Wordpress ACF Repeater field. Worked great thank you very much for this.
@rboatright
I don't know why I didn't notice this before, but you aren't using the $delimiter
passed as a parameter for the header columns. Wouldn't they usually be the same delimiter as the rest of the file?
Edit: Doh! I remember having thought about this last time. I see what it's doing now. I'm passing in the "headers" via string which is comma delimited. Thanks!
Hi guys,
I have this result:
Array ( [0] => Array ( [cod_piesa] => gl [ lungime] => 5000 [ latime] => 3000 [ inaltime] => 150 ) [1] => Array ( [cod_piesa] => fd [ lungime] => 3000 [ latime] => 2000 [ inaltime] => 100 ) )
What I would like to do is to insert the above results in a table like this:
$line = 0
$part = GL
$cota = lungime
$value = 5000
then to insert another row in mysql
$line = 0
$part = GL
$cota = latime
$value = 3000
and so on with each line basically I have a component code with different dimensions, instead of inserting in a huge table in mysql I want to add it as a list with while or something.
Thank you very much!
This is what I have in the csv
cod_piesa, lungime, latime, inaltime
gl, 5000, 3000, 150
fd, 3000, 2000, 100
Thank you very much, saved me a lot of time and probably got better than what I would do.
A little trick:
$formatter = function($value, $delim = ',', $enclosure = '"', $escape = '\\') use (&$header) {
if (!$header) {
$header = array_map('trim', str_getcsv($value, $delim, $enclosure, $escape));
return $header;
} else {
return array_combine($header, array_map('trim', str_getcsv($value, $delim, $enclosure, $escape)));
}
};
$csv = array_map($formatter, file('data.csv'), array() );
than, first element of array (index 0) will be like this:
[0]=>
array(2) {
[0]=>
string(4) "name"
[1]=>
string(6) "number"
}
unset($csv[0]);
and you will recieve useful two-dimensional array
Thank you vary much!
thanks alot, this is exaxtly the function i was looking for.
Perfect, Thank.
Thanks for the function, it works like a charm.
Thanks you very much. I was looking for a solution about to insert CSV file data which contains comma(,) in most of the columns values. I used Csvreader library but by using that I got data by exploding from comma(,) in column value. Now I got your function csv_to_array() and it solved my problem.
All my columns are double quotes ( "name something") and are nicely mapped. Except for the first one, which is correct in the CSV. Anyone got a clue?
[0] => "Contract Number" [1] => Product Type [2] => Internal Title
This happen because your csv file has special encoding, first you need to know what is it, than remove it. In my case was UTF-BOM, so the final version would be like this:
function csv_to_array($filename='', $delimiter=',', $encoding = NULL)
{
if(!file_exists($filename) || !is_readable($filename))
return FALSE;
$header = NULL;
$data = array();
if (($handle = fopen($filename, 'r')) !== FALSE)
{
while (($row = fgetcsv($handle, 1000, $delimiter)) !== FALSE)
{
if(!$header)
if($encoding) {
$header = preg_replace('/' . $encoding . '/', '', $row);
}
else
$header = $row;
else
$data[] = array_combine($header, $row);
}
fclose($handle);
}
return $data;
}
Example:
print_r(csv_to_array('example.csv',,'[\x80-\xFF]')); // This will remove UTF-8 encoding
print_r(csv_to_array('example.csv', ',','[\x80-\xFF]'));
Thanks!
I have tried something like 3 different libraries for codeigniter with no success. Yours is the first one that works perfect without a touch.
THANK YOU!
Hi Thanks for the script :)
I will like to know how to make a foreach loop through the array? because I will like to echo the result out in a table
Sure, here's a simple, primitive example (code untested):
<?php
$data = csv_to_array('example.csv');
echo "<table>";
foreach ($data as $row) {
echo "<tr>";
foreach ($row as $column) {
echo "<td>$column</td>";
}
echo "</tr>";
}
echo "</table>";
Thank you so much. 😊👍
Hi agaín :)
In the csv file there are two columns ,name and numbers, I will like do use the PHP max() Function to get the highest value in an array of the cummum number?
How can i do that?
There's many ways you can achieve that, I'd suggest reading through this tutorial, or picking up a good book on the PHP language. With a little time, it's easy to pick up the basics.
Thanks I do know some basic PHP and i have made this task, justmore simple, without the csv file, but this is a little more advanced for me :)
<style> table { font-family: arial, sans-serif; border-collapse: collapse; width: 100%; }td, th {
border: 1px solid #dddddd;
text-align: left;
padding: 8px;
}
</style>
"; echo "Det lavest Tempartur er: ". (min($temp_array)). "°
"; echo " "; $Mtemp = array( "78, 60, 62, 68, 71, 68, 73, 85, 66, 64, 76, 63, 81, 76, 73, 68, 72, 73, 75, 65, 74, 63, 67, 65, 64, 68, 73, 75, 79, 73, 45"); $datesOFM = array('01-01-2011, 02-01-2011, 03-01-2011, 04-01-2011, 05-01-2011, 06-01-2011, 07-01-2011, 08-01-2011, 09-01-2011, 10-01-2011,11-01-2011, 12-01-2011, 13-01-2011, 14-01-2011, 15-01-2011,16-01-2011, 17-01-2011, 18-01-2011, 19-01-2011, 20-01-2011, 21-01-2011, 22-01-2011, 23-01-2011, 24-01-2011, 25-01-2011, 26-01-2011, 27-01-2011, 28-01-2011, 29-01-2011, 30-01-2011, 31-01-2011'); echo " "; foreach($Mtemp as $key => $value) { echo "" . ""; } echo "
Dato | Tempertur |
---|---|
" . $datesOFM[$key] . " | " . $Mtemp[$key] . " |
Thanks @rboatright
As of PHP 8.0, you can set the length to 0 (or null
, or omit it entirely) for the fgetcsv()
function if you don't want to limit the maximum line length.
Hi
If you want to convert text file into array please follow below link, on this link you can find complete code with live demo.
You can try online with link link.
Convert text file into array