How to Format CSV to ARRAY? - php

Can someone show me how to easily format an array with values like this?
I have a CSV file with values like below:
27383,15.99
80448,19.99
132876,11.99
150438,120
This is the format I would like:
$array[0]['id'] = 27838
$array[0]['price'] = 15.99
$array[1]['id'] = 80448
$array[2]['price'] = 19.99
What I have now is:
$data = file_get_contents('id_and_price.csv');
$data = explode(',', $data);
print_r($data);
//foreach($data as $d) {
// echo $d;
//}

You can do this quite easily with fgetcsv():
$arr = array();
$header = array('id', 'price');
$file = fopen('id_and_price.csv', 'r');
while($item = fgetcsv($file))
{
$arr[] = array_combine($header, $item);
}
print_r($arr);

<?php
$f = fopen('filename', 'r');
$arr = array();
while ($l = fgetcsv($f)) {
$arr[] = array_combine(array('id', 'price'), $l);
}
var_dump($arr);
?>

you need to use php explode...
http://php.net/manual/en/function.explode.php
$csv = "piece1,piece2,piece3,piece4,piece5,piece6";
$array = explode(",", $csv);
echo $array[0]; // piece1
echo $array[1]; // piece2

Related

Converting array in Json PHP output not as expected

I have some problem when I convert an PHP array to Json. for more contex this is the code:
`<?php
$Users = array();
$file = fopen('usersFile.csv', 'r');
$row = fgets($file);
$ColumnKeys = explode(',', $row);
while (!feof($file)) {
$row = fgets($file);
$userData = explode(',', $row);
for ($i=0; $i<sizeof($columnkeys); $i++) {
$user[$columnKeys[$i]] = $userData[$i];
}
array_push($Users, $user);
}
fclose($file);
echo json_encode($Users);
?>`
The csv file containing the user data is this:
id,name,docNumber,dateBirth
1,Mario Mario,1694370,06/11/1953
2,Pau Pep,1725614,24/04/1964
The output look like this:
[{"id":"1","name":"Mario Mario","docNumber":"1694370","dateBirth\r\n":"06\11\1953\r\n"}, {"id":"2","name":"Pau Pep","docNumber":"1725614","dateBirth\r\n":"24\04\1964\r\n"}]
I don't know why in the output the $Users array contain Metacharacter in the dateBirth and their value. Is driving me mad.
it seems there is an option for json_encode called JSON_UNESCAPED_SLASHES
<?php
$Users = array();
$file = fopen('usersFile.csv', 'r');
$row = fgets($file);
$columnKeys = explode(',', trim($row));
while (!feof($file)) {
$row = fgets($file);
$userData = explode(',', trim($row));
for ($i=0; $i<sizeof($columnKeys); $i++) {
$user[$columnKeys[$i]] = $userData[$i];
}
array_push($Users, $user);
}
fclose($file);
echo json_encode($Users, JSON_UNESCAPED_SLASHES);
?>
Output:
[{"id":"1","name":"Mario Mario","docNumber":"1694370","dateBirth":"06/11/1953"},{"id":"2","name":"Pau Pep","docNumber":"1725614","dateBirth":"24/04/1964"}]

Group by a column from csv and sum the values from another (PHP)

I have a csv like this:
25/07/2016 3
25/07/2016 4
26/07/2016 4
26/07/2016 1
And the output that i expect, it have to be like this
25/07/2016 7
26/07/2016 5
I want to do this only using PHP.
I have to mention that i am not using mysql and i don't want to.
Is there a solution to do that?
Try something like this. This is just an edited version from this similar post.
$my_file = fopen('file.csv', 'rb');
$my_array = array();
while($row = fgetcsv($my_file)) {
$my_array[$row[0]] += $row[1];
}
"25/07/2016","3"
"25/07/2016","4"
"26/07/2016","4"
"26/07/2016","1"
For e.g. Let's say you have CSV file that contains data as above.
$arr = array();
$handle = fopen("example.csv", "r");
while(!feof($handle))
{
$arrOfCSVLine = fgetcsv($handle);
$date = $arrOfCSVLine[0];
$no = $arrOfCSVLine[1];
if(!array_key_exists($data,$arr))
{
$arr[$date] = $no;
}
else
{
$arr[$date] += $no;
}
}
echo '<pre>';
print_r($arr);
check this code..
$finalOutput = array();
$file = fopen('myCSVFile.csv', 'r');
while (($line = fgetcsv($file)) !== FALSE) {
if(isset($finalOutput[$line[0]])){
$finalOutput[$line[0]] = $line[1] + $finalOutput[$line[0]];
} else {
$finalOutput[$line[0]] = $line[1];
}
}
print_r($finalOutput);

Remove blank from text file

I want to remove blank line from this text file :
test1
test2
test3
test4
So I try this code in PHP :
$file = __DIR__.$namefile;
foreach ($file as $k => $v) {
if (!trim($v))
unset($lines[$k]);
}
$f = fopen($file, "r");
$array1 = array();
//Extract all url from file
while ( $line = fgets($f, 1000) ) {
$nl = mb_strtolower($line,'UTF-8');
$array1[] = $nl;
}
But it does not work. Thanks for your help !
How about exploding each new line and checking if it's empty?
<?php
$content = fopen($file = __DIR__.$namefile, "r");
$lines = explode("\n", $content);
$result = array();
foreach ($lines AS $line) {
if (!empty($line)) {
$result[] = $line;
}
}
$result = implode("\n", $result);
Or, as Henders suggests, look at https://stackoverflow.com/a/7972266/1441858:
<?php
$content = fopen($file = __DIR__.$namefile, "r");
$lines = explode("\n", $content);
$result = array_filter($lines, 'trim');
$result = implode("\n", $result);
$file = __DIR__.$namefile;
$f = fopen($file, "r");
$array1 = array();
//Extract all url from file
while ( $line = fgets($f, 1000) ) {
$nl = mb_strtolower($line,'UTF-8');
if (trim($line) != "") {
$array1[] = $nl;
}
}
fclose($f);
$file = __DIR__.$namefile;
$lines = explode("\n", file_get_contents($file));
$result = array_filter($lines);
echo implode("\n", $result);
file_put_contents($file, implode("\n", $result)); //save
Or use:
$result = array_filter($lines, 'trim');
If there can be whitespaces in blank lines.

php to convert CSV to JSON with nested objects

I have csv file like this:
data,IF,VVS1,VVS2
D,23,17,15
E,17,15,14
What i need is to convert this CSV into JSON but to look like this:
{"D" : {"IF":"23", "VVS1":"17", "VVS2":"15"},"E" : {"IF":"17", "VVS1":"15", "VVS2":"14"}}
Any help?
/* Lets suppose, the csv file is, mydata.scv */
<?php
$mydata = array();
if($file = fopen("mydata.csv","r")){
$csvheaders = fgetcsv($file);
while(($row = fgetcsv($file)) !== FALSE){
$arr = array();
for($i=1; $i<count($csvheaders); $i++){
$arr[$csvheaders[$i]] = $row[$i];
}
$mydata[$row[0]] = $arr;
}
fclose($file);
// encode $mydata array into json to get result in the required format
$mydatainformat = json_encode($mydata);
echo $mydatainformat; // This is your output.
}
?>
Maybe help you, but I recommend add error handling.
<?php
$file = fopen('test.csv', 'r');
$header = fgetcsv($file);
array_shift($header);
$data = array();
while ($row = fgetcsv($file))
{
$key = array_shift($row);
$data[$key] = array_combine($header, $row);
}
echo json_encode($data);
fclose($file);

PHP : POST-- How to replace defined KEY from ARRAY in a file

I'm a bit lost for I'm "green" in PHP.
Please, may you teach me how to fix this:
on 'POST' --> Replace a specified array key from a file:
(WRONG:)
<?php
$newData = $_POST["sendData"];
if(isset($_POST['sendData'])){
$file = fopen('fileToOpen.php', 'a');
foreach($file as $key => $val)
{
$data[$key] = explode("|", $val);
}
for($k = 0; $k < sizeof($file); $k++)
{
unset($data[$k][3]);
}
$data[$k][3] = "$newData";
fwrite($file, $data[$k][3]);
fclose ($file);
}
?>
That's wrong as it continues to write:
data1|data2|data3|oldDatanewData
instead of rewrite:
data1|data2|data3|newData
Is there any other technique to achieve something similar? Perhaps with file_put_contents? Am I missing implode?
Thanks!
Dunno what are you asking for but perhaps you only need to serialize and unserialize the array.
$data_array = unserialize(file_get_contents('fileToOpen.php'));
$data_array[$key_you_want_to_change] = $new_data;
file_put_contents('fileToOpen.php', serialize($data_array));
$newData = $_POST['sendData'];
if(isset($_POST['sendData'])){
$file = "fileToOpen.php";
$oldData = file_get_contents($file);
$oldData = eregi_replace("\n","",$oldData);
$FullDataArray = explode("?",$oldData);
$oldDataArray = explode("|",$FullDataArray[1]);
$oldDataArray[3] = $newData;
$newDataString .= "
foreach($oldDataArray as $key=>$val) {
$newDataString .= $val;
if($key!="3") {
$newDataString .= "|";
}
}
$fh = fopen($file, 'w');
fwrite($fh,$newDataString);
fclose($fh);
}
?>

Categories