Give names to array keys - php

So I have this code:
<?php
$csv = array();
$lines = file('file.csv', FILE_IGNORE_NEW_LINES);
foreach ($lines as $key => $value)
{
$csv[$key] = str_getcsv($value);
}
echo '<pre>';
print_r($csv);
echo '</pre>';
?>
which gives me the following
[0] => Array
(
[0] => value1
[1] => value2
[2] => value3
[3] => value4
How can I name my keys? so I don't see 0-1-2-3 but Name1-Name2-Name3 etc.
Like This:
[0] => Array
(
[Name0] => value1
[Name1] => value2
[Name2] => value3
[Name3] => value4

function csvToArray($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, 0, $delimiter)) !== FALSE) {
if (count($row) > 0 && !is_null($row[0])) {
if (!$header) {
$header = $row;
} else {
$data[] = array_combine($header, $row);
}
}
}
fclose($handle);
}
return $data;
}
Try this function
$filename is the full path to the file
also add in csv as first line keys you want to have and function will use this first line for keys
csv example:
"id","country","city"
"1","us","abanda"
"2","us","abbeville"

Now I understand!
All you need to do in this case is concatenate a string literal onto the front of the key that you generate, like this :-
<?php
$csv = array();
$lines = file('file.csv', FILE_IGNORE_NEW_LINES);
foreach ($lines as $key => $value)
{
$csv['Name'.$key] = str_getcsv($value);
}
echo '<pre>';
print_r($csv);
echo '</pre>';
?>

$keys = ['Name1', 'Name2', 'Name3', 'etc'];
$csv[$key] = array_combine($keys, str_getcsv($value));
This worked
Thanks Mark Baker

Related

How to dynamically get column value from csv file using php

i have two columns in csv file Name and Phone . If i given phone number as a variable $searchStr = "6059574150"; it has to find number in csv file and i need that contact name to get access dynamicaly like this $data['Name'] instead of $data['0']
MY php code
$header = array();
$final_result = array();
$file = fopen('example.csv', 'r');
if($file){
$row = 1;
while ($data = fgetcsv($file, 10000, ",")){
if($row == 1){
$header = array_values($data);
}
else{
$final_result[] = array_combine($header, array_values($data));
}
$row++;
}
}
echo "<pre>";
print_r($final_result);
my output is like this
Array
(
[0] => Array
(
[Names] => MICHAEL
[Phone] => 6059342614
)
[1] => Array
(
[Names] => GLENN
[Phone] => 6056296061
)
)
how to directly access column ? like this $data['Name']
If phone numbers are unique, you could do something like this:
<?php
$final_result = array();
$file = fopen('example.csv', 'r');
if($file) {
$header = fgetcsv($file, 10000, ",");
while ($data = fgetcsv($file, 10000, ",")) {
$final_result[$data[1]] = $data[0];
}
}
?>
If you have more than one name (person) for each phone number, you can concatenate them $final_result[$data[1]] .= ',' . $data[0];.
Example result:
array (
phone1 => 'name1',
phone2 => 'name2',
phone3 => 'name3',
)
To search a name from a phone number you have to do: $final_result[phone_number] and you get the name.
In your output array "$final_result" you can look for a Name by phone number this way:
$foundKey = array_search('pone_number_to_search', array_column($final_result, "Phone"));
$foundNames = $final_result[$foundKey]["Names"];

PHP CSV to associative array with top row as keys and columns as value arrays

I am trying to create a multidimensional array using CSV file so that for example:
"a","b","c"
1,2,3
4,5,6
would return as:
array(
'a' => array(1, 4),
'b' => array(2, 5),
'c' => array(3, 6),
)
But the code I have:
<?php
function readCSV($csvFile) {
$aryData = [];
$header = NULL;
$handle = fopen($csvFile, "r");
if($handle){
while (!feof($handle)){
$aryCsvData = fgetcsv($handle);
if(!is_array($aryCsvData)){
continue;
}
if(is_null($header)){
$header = $aryCsvData;
}
elseif(is_array($header) && count($header) == count($aryCsvData)){
$aryData[] = array_combine($header, $aryCsvData);
}
}
fclose($handle);
}
return $aryData;
}
print_r(readCSV("Book1.csv"));
?>
Returns it as:
Array(
[0] => Array ( [a] => 1 [b] => 2 [c] => 3 )
[1] => Array ( [a] => 4 [b] => 5 [c] => 6 )
)
Would appreciate any help!
Instead of building the end array as you go along. This code reads the header row before the loop, then just reads all of the data lines into another array. It then combines each element of the header array with the matching column from the data array (using array_column() and the position of the header element)...
function readCSV($csvFile) {
$aryData = [];
$output = [];
$header = NULL;
$handle = fopen($csvFile, "r");
if($handle){
$header = fgetcsv($handle);
while ($aryData[] = fgetcsv($handle));
foreach ( $header as $key=>$label) {
$output[$label] = array_column($aryData, $key);
}
fclose($handle);
}
return $output;
}
Read the first row of the file and create the associative array with empty columns. Then read each remaining row and loop through it, pushing the values onto the column arrays.
<?php
function readCSV($csvFile) {
$aryData = [];
$handle = fopen($csvFile, "r");
if($handle){
$headerRow = fgetcsv($handle);
if (!$headerRow) {
return $aryData;
}
foreach ($headerRow as $colname) {
$aryData[$colname] = [];
}
while ($aryCsvData = fgetcsv($handle)){
foreach ($headerRow as $colname) {
$aryData[$colname][] = each($aryCsvData);
}
}
fclose($handle);
}
return $aryData;
}

How to split array key and value in sperate keys and values

I'm trying to get a useable array.
This is what I did to get the following array from my .csv file.
$csv = array_map('str_getcsv', file($file));
array_walk($csv, function(&$a) use ($csv) {
$a = array_combine($csv[0], $a);
});
array_shift($csv);
Right now I've got an array with these keys and values:
[0] => Array
(
[Label;Account;Registered;Licensed;User;UserLicense] => Test;Test;No;No;test;no;
)
And I want to get an array like:
[0] => Array
(
[Label] => Test
[Account] => Test
[Registered] => No
[Licensed] => No
[User] => test
[UsreLicense] => no
)
Can anyone help me?
Thanks.
class arrCsv {
private $arr;
private function getValFromArray($item, $key) {
$arrKeys = explode(';', $key);
$arrVal = explode(';', $item);
array_pop($arrVal); // remove last empty item
$this->arr[] = array_combine($arrKeys, $arrVal);
}
function setNewArr($arItems) {
array_walk_recursive($arItems, array($this, 'getValFromArray'));
}
function getNewArr() {
return $this->arr;
}
}
$r = new arrCsv;
$r->setNewArr($csvArray);
$vals = $r->getNewArr();
The answer I found:
$usersCsv = array();
if (($handle = fopen($file, "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ";")) !== FALSE) {
$usersCsv[] = $data;
array_walk($usersCsv, function(&$a) use ($usersCsv) {
$a = array_combine($usersCsv[0], $a);
});
}
fclose($handle);
array_splice($usersCsv, 0, 1);
}
Thanks for the help anyways!

Get Value Only From Multidemensional Code after a csv parse

I have been trying to get the value of my combined rate, but running into some trouble with simply getting the value :
Array ( [0] => Array ( [ZipCode] => 01014 [CombinedRate] => 0.0625 ) ) <--- this is the array that is printed.
Here is the full code:
<?php
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;
}
$zipsearch = csv_to_array($_SERVER['DOCUMENT_ROOT'].'/textfiles/taxes.csv');
function search($array, $key, $value)
{
$results = array();
if (is_array($array)) {
if (isset($array[$key]) && $array[$key] == $value) {
$results[] = $array;
}
foreach ($array as $subarray) {
$results = array_merge($results, search($subarray, $key, $value));
}
}
return $results;
}
$valueofzip = search( $zipsearch, 'ZipCode', '01014');
print_r($valueofzip)
/*
Need Code To print Just value of that array
*/
?>
I just need the value of the combined rate after the zipcode is found from the array that is printed, but for whatever reason I am just missing it,
How do I just get the value of "Combined Rate" from this array that is printed : Array ( [0] => Array ( [ZipCode] => 01014 [CombinedRate] => 0.0625 ) )
Essentially this page will print out a single tax rate
It looks like the value that you are trying to retrieve is simply:
$valueofzip[0]['CombinedRate']
i.e. the value with the key "CombinedRate" in the zeroth element of $valueofzip.
If you are anticipating there being more than one array returned by your search function, then a foreach loop would be more appropriate:
foreach($valueofzip as $zip) {
if (isset($zip['CombinedRate'])) echo $zip['CombinedRate'];
}
Depending on exactly what you want to do with the value, you might also want to take a look at array_walk, array_map, etc. in the documentation. They can be used to traverse the array and apply a callback function to each element. For example:
$valueofzip = array(array("ZipCode" => 01014, "CombinedRate" => 0.0625),
array("ZipCode" => 02025, "CombinedRate" => 0.125 ));
$combined_rates = array_map(function($x) { if (isset($x['CombinedRate'])) return $x['CombinedRate']; }, $valueofzip));
print_r($combined_rates);
Output:
Array
(
[0] => 0.0625
[1] => 0.125
)

PHP CSV string to array

I'm trying to parse a CSV string to an array in PHP. The CSV string has the following attributes:
Delimiter: ,
Enclosure: "
New line: \r\n
Example content:
"12345","Computers","Acer","4","Varta","5.93","1","0.04","27-05-2013"
"12346","Computers","Acer","5","Decra","5.94","1","0.04","27-05-2013"
When I try to parse it like this:
$url = "http://www.url-to-feed.com";
$csv = file_get_contents($url);
$data = str_getcsv($csv);
var_dump($data);
The last and first element are concatenated in one string:
[0]=> string(5) "12345"
...
[7]=> string(4) "0.04"
[8]=> string(19) "27-05-2013
"12346""
How can I fix this? Any help would be appreciated.
Do this:
$csvData = file_get_contents($fileName);
$lines = explode(PHP_EOL, $csvData);
$array = array();
foreach ($lines as $line) {
$array[] = str_getcsv($line);
}
print_r($array);
It will give you an output like this:
Array
(
[0] => Array
(
[0] => 12345
[1] => Computers
[2] => Acer
[3] => 4
[4] => Varta
[5] => 5.93
[6] => 1
[7] => 0.04
[8] => 27-05-2013
)
[1] => Array
(
[0] => 12346
[1] => Computers
[2] => Acer
[3] => 5
[4] => Decra
[5] => 5.94
[6] => 1
[7] => 0.04
[8] => 27-05-2013
)
)
I hope this can be of some help.
You should use fgetcsv. Since you cannot import a file as a stream because the csv is a variable, then you should spoof the string as a file by using php://temp or php://memory first:
$fp = fopen("php://temp", 'r+');
fputs($fp, $csvText);
rewind($fp);
Then you will have no problem using fgetcsv:
$csv = [];
while ( ($data = fgetcsv($fp) ) !== FALSE ) {
$csv[] = $data;
}
fclose($fp)
$data will be an array of a single csv line (which may include line breaks or commas, etc), as it should be.
Caveat: The memory limit of php://temp can be controlled by appending /maxmemory:NN, where NN is the maximum amount of data to keep in memory before using a temporary file, in bytes. (the default is 2 MB) http://www.php.net/manual/en/wrappers.php.php
Handy oneliner:
$csv = array_map('str_getcsv', file('data.csv'));
I have used following function to parse csv string to associative array
public function csvToArray($file) {
$rows = array();
$headers = array();
if (file_exists($file) && is_readable($file)) {
$handle = fopen($file, 'r');
while (!feof($handle)) {
$row = fgetcsv($handle, 10240, ',', '"');
if (empty($headers))
$headers = $row;
else if (is_array($row)) {
array_splice($row, count($headers));
$rows[] = array_combine($headers, $row);
}
}
fclose($handle);
} else {
throw new Exception($file . ' doesn`t exist or is not readable.');
}
return $rows;
}
if your csv file name is mycsv.csv then you call this function as:
$dataArray = csvToArray(mycsv.csv);
you can get this script also in http://www.scriptville.in/parse-csv-data-to-array/
A modification of previous answers using array_map.
Blow up the CSV data with multiple lines.
$csv = array_map('str_getcsv', explode("\n", $csvData));
Slightly shorter version, without unnecessary second variable:
$csv = <<<'ENDLIST'
"12345","Computers","Acer","4","Varta","5.93","1","0.04","27-05-2013"
"12346","Computers","Acer","5","Decra","5.94","1","0.04","27-05-2013"
ENDLIST;
$arr = explode("\n", $csv);
foreach ($arr as &$line) {
$line = str_getcsv($line);
}
If you need a name for the csv columns, you can use this method
$example= array_map(function($v) {$column = str_getcsv($v, ";");return array("foo" => $column[0],"bar" => $column[1]);},file('file.csv'));
If you have carriage return/line feeds within columns, str_getcsv will not work.
Try https://github.com/synappnz/php-csv
Use:
include "csv.php";
$csv = new csv(file_get_contents("filename.csv"));
$rows = $csv->rows();
foreach ($rows as $row)
{
// do something with $row
}
You can convert CSV string to Array with this function.
function csv2array(
$csv_string,
$delimiter = ",",
$skip_empty_lines = true,
$trim_fields = true,
$FirstLineTitle = false
) {
$arr = array_map(
function ( $line ) use ( &$result, &$FirstLine, $delimiter, $trim_fields, $FirstLineTitle ) {
if ($FirstLineTitle && !$FirstLine) {
$FirstLine = explode( $delimiter, $result[0] );
}
$lineResult = array_map(
function ( $field ) {
return str_replace( '!!Q!!', '"', utf8_decode( urldecode( $field ) ) );
},
$trim_fields ? array_map( 'trim', explode( $delimiter, $line ) ) : explode( $delimiter, $line )
);
return $FirstLineTitle ? array_combine( $FirstLine, $lineResult ) : $lineResult;
},
($result = preg_split(
$skip_empty_lines ? ( $trim_fields ? '/( *\R)+/s' : '/\R+/s' ) : '/\R/s',
preg_replace_callback(
'/"(.*?)"/s',
function ( $field ) {
return urlencode( utf8_encode( $field[1] ) );
},
$enc = preg_replace( '/(?<!")""/', '!!Q!!', $csv_string )
)
))
);
return $FirstLineTitle ? array_splice($arr, 1) : $arr;
}
Try this, it's working for me:
$delimiter = ",";
$enclosure = '"';
$escape = "\\" ;
$rows = array_filter(explode(PHP_EOL, $content));
$header = NULL;
$data = [];
foreach($rows as $row)
{
$row = str_getcsv ($row, $delimiter, $enclosure , $escape);
if(!$header) {
$header = $row;
} else {
$data[] = array_combine($header, $row);
}
}

Categories