Append brackets at the end in the CSV file - php

At the beginning and at ending of the contents I have to append the brackets my csv file looks like this
date1,success,failure,count
1427653800,95,65,160
1427653800,30,10,40
1427740200,10,8,18
1427740200,30,38,68
1427826600,38,20,58
1427826600,60,10,70
1427653800,15,15,30
1427653800,10,10,20
After adding brackets the contents should look like this: [1427653800,95,65,160]
My php code is below:
<?php
$list = array ('date1', 'success', 'failure','count');
$sql = "SELECT (SUBSTRING(UNIX_TIMESTAMP(date1),1,10)),success,failure,count from h_statistics;";
$users_profile_user_id = mysqli_query($conn, $sql);
$fp = fopen("data.csv", "w");
fputcsv($fp, $list);
while($row = mysqli_fetch_array($users_profile_user_id, MYSQLI_ASSOC))
{
fputcsv($fp, $row);
}
fclose($fp);
?>
this is my conn.php file ,please suggest me on this

it is better to use this query
$sql = "SELECT CONCAT('[','',(SUBSTRING(UNIX_TIMESTAMP(date1),1,10))),success,failure,CONCAT(count,'',']') from h_statistics";
it give you result like [1427653800,95,65,160] so no need to do any code in you while loop

Try to append and prepend the brackets :
$row[0] = '['.$row[0];
$row[3] .= ']';
fputcsv($fp, $row);

try with my function which is adding your text to the first and last element of the associative array:
<?php
function array_brackets($array,$prefix,$suffix){
//add prefix to the first element
end($array);
$key = key($array);
$array[$key] = $prefix . $array[$key];
//add sufix to the last element
reset($array);
$key = key($array);
$array[$key] = $array[$key] . $suffix;
return $array;
}
$list = array ('date1', 'success', 'failure','count');
$sql = "SELECT (SUBSTRING(UNIX_TIMESTAMP(date1),1,10)),success,failure,count from h_statistics;";
$users_profile_user_id = mysqli_query($conn, $sql);
$fp = fopen("data.csv", "w");
fputcsv($fp, $list);
while($row = mysqli_fetch_array($users_profile_user_id, MYSQLI_ASSOC))
{
fputcsv($fp, array_brackets($row,"[","]"));
}
fclose($fp);
?>

Please run this code and give me the output:
<?php
$list = array ('date1', 'success', 'failure','count');
$sql = "SELECT (SUBSTRING(UNIX_TIMESTAMP(date1),1,10)),success,failure,count from h_statistics;";
$users_profile_user_id = mysqli_query($conn, $sql);
//$fp = fopen("data.csv", "w");
//fputcsv($fp, $list);
while($row = mysqli_fetch_array($users_profile_user_id, MYSQLI_ASSOC))
{
//fputcsv($fp, array_brackets($row,"[","]"));
print_r($row);
exit;
}
//fclose($fp);
?>

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"}]

Store data into array variable php

If i echo inside the while loop i get 4,2 values and if i echo outside the while loop then i only get 2. I want to get the data from $row into the values array. is something missing in this code?
$query = oci_parse($con, "SELECT count(*) FROM Counter GROUP BY Blog_name");
oci_execute($query);
while($row = oci_fetch_array($query))
{
$s = $row[0].',';
$values = explode(',', $s);
echo $values[0]; // 4
echo $values[1]; // 2
}
echo $values[0]; // 2
echo $values[1]; // 2
Try this,
$Values = array();
while($row = oci_fetch_array($query))
{
$Values[] = $row[0];
}
echo $Values[0];
First, $values as you're using it is just a string, and is not an array.
Try adding before the while loop.
$values = array();
Second, there's really no need to use explode here, it's an unnecessary step. If you only want the first column in the row, you can simply add that column to $values. (Currently you are overwriting the contents of $values at each iteration of the loop because you are missing the [].)
$values[] = $row[0];
If you're trying to put ALL of the columns in each row into values, try:
$values[] = $row;
If you're trying to individually put the contents of each column into it's own index in $values, try:
while($row = oci_fetch_array($query))
{
foreach($row as $column)
{
$values[] = $column;
}
}
Do like this:
$s = array();
while($row = oci_fetch_array($query)) {
$s[] = $row[0];
}
echo $s[0];
print_r($s);
$query = oci_parse($con, "SELECT count(*) FROM Counter GROUP BY Blog_name");
oci_execute($query);
$values = array();
while($row = oci_fetch_array($query))
{
$values[] = $row[0];
}
print_r($values);

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);

Exclude last comma in php array

I have a simple database connection:
$rowdata = mysql_query("SELECT * FROM table_names");
while($row = mysql_fetch_array($rowdata)) {
echo "".$row['name'].",";
}
I would like it to print out:
Adam, Sophia, Tom, Brian
instead of:
Adam, Sophia, Tom, Brian,
How do I exclude the last comma in the best way?
$rowdata = mysql_query("SELECT name FROM table_names");
$names = array();
while($row = mysql_fetch_array($rowdata)) {
$names[] = $row['name'];
}
echo implode(', ', $names);
Instead of echoing it straight out, put it into a variable (named $values perhaps) then do:
$values = rtrim($values,",");
Print the comma before each entry and omit the first one:
$first = TRUE;
while(($row = mysql_fetch_array($rowdata)) !== FALSE) {
if(!$first) echo ',';
echo htmlspecialchars($row['name']);
$first = FALSE;
}
Another way would be to use extract echoing the first line from the loop, that way the if statement does not have to be evaluated each iteration (premature optimization ftw!):
if(($row = mysql_fetch_array($rowdata)) !== FALSE)
echo htmlspecialchars($row['name']);
while(($row = mysql_fetch_array($rowdata)) !== FALSE) {
echo ',', htmlspecialchars($row['name']);
}
And finally you can do it in mysql:
select group_concat(name) from table_names
In full this would become:
$rowdata = mysql_query("SELECT group_concat(name) as names FROM table_names");
while($row = mysql_fetch_array($rowdata)) {
echo $row['names'];
}
$rowdata = mysql_query("SELECT * FROM table_names");
$names = array();
while($row = mysql_fetch_array($rowdata)) {
$names[] = $row['name'];
}
echo implode( $names, ',' );
By the way, if you're only using the 'name' column, it's better to do SELECT name FROM ..
Make it ..
$names = array();
while ( $row = mysql_fetch_array( $rowdata ) ) {
$names[] = $row['name'];
}
$names = implode(', ', $names);
echo $names;

invalid argument when imploding in php

Im getting invalid argument error when running the following code. Im trying to change the value of a line in the $info array, then implode it, implode its parent array, and then save the whole shebang back to whence it came.
$rowpre = $_GET['row'];
$newfieldvalue = $_GET['nfv'];
$row = --$rowpre;
$data = file_get_contents("temp.php");
$csvpre = explode("###", $data);
$i = 0;
foreach ( $csvpre AS $key => $value){
$i++;
if($i = $row){
$info = explode("%%", $value);
$info[$target] = $newfieldvalue;
$presave = implode("%%", $info);
}
}
$save = implode("###", $presave);
$fh = fopen("temp.php", 'w') or die("can't open file");
fwrite($fh, $save);
fclose($fh);
update below
$rowpre = $_GET['row'];
$newfieldvalue = $_GET['nfv'];
$target = $_GET['target'];
$row = --$rowpre;
$data = file_get_contents("temp.php");
$csvpre = explode("###", $data);
$i = 0;
foreach ( $csvpre AS $key => $value){
$i++;
if($i == $row){
$info = explode("%%", $value);
$info[$target] = $newfieldvalue;
$csvpre[$key] = implode("%%", $info);
}
}
$save = implode("###", $csvpre);
$fh = fopen("temp.php", 'w') or die("can't open file");
fwrite($fh, $save);
fclose($fh);
Target is the field within the selected Row that i wish to update with the newfieldvalue data.
$save = implode("###", $presave);
At that point, $presave is a string, and should be an array to work with implode. Create an array where you push the $presave-values, and implode that one.
$presave contains the last processed line (i.e. a string) and implode expects an array. To store the line back in the original array, change:
$presave = implode("%%", $info);
to:
$csvpre[$key] = implode("%%", $info);
And to convert the whole CSV array into a string, change:
$save = implode("###", $presave);
to:
$save = implode("###", $csvpre);
And one more problem:
if($i = $row){
should be:
if($i == $row){
because you want to compare the variables, not assign $i.

Categories