Convert CSV into Array - php

I have a csv file that looks like this:
Did,status
"123","Active"
"456","Not-Active"
"789","Active"
....and so on
I would like to be able to convert it into an array that looks like this:
$DidStatus = array("123"=>"Active", "456"=>"Not-Active", "789"=>"Active");
I tried this but it's not what I'm looking for:
$file = file_get_contents("test.csv");
$data = array_map("str_getcsv", preg_split('/\r*\n+|\r+/', $file));
print_r($data);
but the output is not the one I'm looking for:
Array
(
[0] => Array
(
[0] => Did
[1] => status
)
[1] => Array
(
[0] => 123
[1] => Active
)
[2] => Array
(
[0] => 456
[1] => Not-Active
)
[3] => Array
(
[0] => 789
[1] => Active
)
[4] => Array
(
[0] =>
)
)

Look into fgetcsv()
<?php
$handle = fopen("test.csv", "r");
$result = Array();
fgetcsv($handle); //Removes the first line of headings in the csv
while($data = fgetcsv($handle)) {
$result[$data[0]] = $data[1];
}
print_r($result); //the result
?>

There are other ways to do it, but given your current code, just extract an array of the 1 values and index it by the 0 values.
unset($data[0]); //If needed to remove the header row
$data = array_column($data, 1, 0);
You may consider this as an alternate for the first step (not sure if FILE_IGNORE_NEW_LINES is absolutely necessary):
$data = array_map('str_getcsv', file('test.csv', FILE_IGNORE_NEW_LINES));

Look into fgetcsv. That is meant to be used for something like this.
$arr = array();
$file = fopen('test.csv', 'r');
while (($result = fgetcsv($file)) !== FALSE)
{
$arr[] = $result;
}
fclose($file);

You can use this package league/csv and you can find instructions on how to use it here - one of the first examples shows how to convert csv to array

Related

Read data from CSV into a single array or a single json

I am using jQuery autocomplete function. For it to work I need the json in this format ["Alaska","Alabama","Arkansas"] . Currently I am reading the data from a CSV file. This is my code.
$f = fopen($filename, "r");
while ($row = fgetcsv($f)) {
$out = $row[2];
print_r (explode(" , ",$out));
}
Now I get the output as
Array
(
[0] => Alaska
)
Array
(
[0] => Alabama
)
Array
(
[0] => Arkansas
)
And my Json as
["Alaska"]["Romeo"]["Arkansas"]
How do I convert the array into a simple array like
Array
(
[0] => Alaska
[1] => Alabama
[2] => Arkansas
)
If not into a json like this
["Alaska","Alabama","Arkansas"]
You build an array of values and then put them in json_encode() function.
$data = [];
$f = fopen($filename, "r");
while ($row = fgetcsv($f)) {
$out = $row[2];
$data = array_merge($data, explode(" , ",$out)));
}
echo json_encode($data);
Might be easier to read the file into an arary, map to a function that explodes, then encode and display:
echo json_encode(
array_map(function($v) { return explode(" , ", $v)[2]; }, file($filename))
);

How to separate csv array by column?

I have a giant list in excel, they are just two columns
name type
The file is currently being read:
$lines = array_map('str_getcsv', file('file.csv', FILE_IGNORE_NEW_LINES));
print_r($lines); returns:
name1;type
name2;type2
...
Array ( [0] => Array ( [0] => name1;type1) [1] => Array ( [0] => name2;type2)...
I would like to access separate name and type in an foreach
How can I do this?
Thanks
str_getcsv default delimiter is ',' so you need call it somehow with explicitly specifying ';' as delimeter
for example like this
$myGetCsv = function ($str) {
return str_getcsv($str, ';');
};
$lines = array_map($myGetCsv, file('file.csv', FILE_IGNORE_NEW_LINES));
Use this code for CSV file reading. it ease to use and understand how its work.
if (($handle = fopen('./suppression_invalid_emails.csv', "r")) !== false) {
//getting column name
$column_headers = fgetcsv($handle);
foreach ($column_headers as $header) {
//column as array;
$result[$header] = array();
}
// get data for column;
while (($data = fgetcsv($handle)) !== false) {
$i = 0;
foreach ($result as &$column) {
$column[] = $data[$i++];
}
}
fclose($handle);
echo '<pre>'; print_r($result); echo '</pre>';
}
i use two basic function for this 1st one is fopen for reading file and other is fgetcsv for getting data for column.
and result is:
Array
(
[reason] => Array
(
[0] => Mail domain mentioned in email address is unknown
[1] => Known bad domain
[2] => Known bad domain
)
[email] => Array
(
[0] => muneque#collegeclub.om
[1] => saharfa2000#hatmail.com
[2] => tawheeda81#yahoo.co
)
[created] => Array
(
[0] => 1502644294
[1] => 1502480171
[2] => 1502344320
)
)

How to merge different arrays in a while loop of feof() while using a CSV file?

I am retrieving data from a CSV file and I want to merge all different arrays in one array so that I can perform a sort on it. My array comes like this:
Array ( [0] => kim [1] => abc [2] => xyz )
Array ( [0] => roger [1] => def [2] => ghi )
...
There are more arrays like this and I want to merge all of them in one array and sort it. Currently my code is the following:
<?php
$file = fopen("file.csv","r");
while(! feof($file))
{
$array= fgetcsv($file);
print_r($array);
echo "<br/>";
}
fclose($file);
?>
Please help. Thank You
did you try something like this :
<?php
$file = fopen("file.csv","r");
$array = [];
while(! feof($file))
{
$array = array_merge($array, fgetcsv($file));
}
sort($array);
print_r($array);
fclose($file);
?>

How to break an array and use part of it with PHP

I am new to this so your help is much needed. I have a CSV file and I need to modify the last column of this CSV. What I did is separated the columns in array using this code below.
<?php
function readCSV($csvFile){
$file_handle = fopen($csvFile,"r");
while (!feof($file_handle)) {
$line_of_text[] = fgetcsv($file_handle, 1024);
}
fclose($file_handle);
return $line_of_text;
}
$csvFile = 'testslash.csv';
$csv = readCSV($csvFile);
print_r($csv);
?>
This is the output i am getting which is fine .. what i want to end up with ex: array 0,2 and array 1,2. i tried array slice but with no avail. any other options?
Array
(
[0] => Array
(
[0] => ABC
[1] => XXX
[2] => 972 54 120000 / 129999
)
[1] => Array
(
[0] => DEF
[1] => XXX
[2] => 972 52 1100180 / 9
)
)
You're saying you want only a specific part of the subarrays.
This is easily done using a foreach loop and a new array.
$resultArray = array();
foreach($cvs as $row)
{
$resultArray[] = $row[2]; //if you dont care about the index of the array
$resultArray[$row[0]] = $row[2]; //if you want to speficy the index as the value of e.g. the first entry of the subarray;
}

PHP, Building ID'd array from non-incremental ID'd CSV

Basically, here is my CSV File:
1,"Gold"
2,"English Version"
10,"Sword+0"
11,"Sword+1"
12,"Sword+2"
And so on, you get the idea. There are other parts where the ID is not incremental, perhaps one is 2899 and then the next one is 3020. I'm trying to build an array from this with fgetcsv();. I can do it fine, but I've failed so far to match up my array IDs with the ID from the CSV.
Here's a simple one that simply builds an incremental array from the file:
$file = fopen("item_proto.csv", "r");
$i = 1;
while(! feof($file)){
$gvar['item'][$i] = (fgetcsv($file));
$i++;
}
fclose($file);
This of course results in:
Array
(
[item] => Array
(
[1] => Array
(
[0] => 1
[1] => Gold
)
[2] => Array
(
[0] => 2
[1] => English Version
)
[3] => Array
(
[0] => 10
[1] => Sword+0
But I'd like [item][x] to match up with [item][x][y].
Try this:
$file = fopen("item_proto.csv", "r");
$i = 1;
while(! feof($file)){
$line = fgetcsv($file);
$gvar['item'][$line[0]] = $line;
$i++;
}
fclose($file);

Categories