Php json_encode from mysql > output without column names - php

this is my code on a php page connected to mysql server.
$temp = array();
while($row = mysqli_fetch_assoc($result)) {
$temp[] = $row;
}
echo json_encode($temp);
The output is:
[{"column1":"1448741941","column2":"951"},{"column1":"1448747281","column2":"862"}]
That's is including the column title + data, and i wanna know how can i get only datas, like
[[1448741941,951],[1448747281,862]]
Thanks for the help!

Here is the quick answer, send in an array with the data only:
$temp = array();
while($row = mysqli_fetch_assoc($result)) {
$temp[] = array( $row['column1'], $row['column2'] );
}
echo json_encode($temp);
Edit You might actually whant this too JSON_NUMERIC_CHECK:
$temp = array();
while($row = mysqli_fetch_assoc($result)) {
$temp[] = array( $row['column1'], $row['column2'] );
}
echo json_encode($temp, JSON_NUMERIC_CHECK);
Another way is this:
$temp[] = array(
intval( $row['column1'] ),
intval( $row['column2'] ) );

Related

PHP - How to merge two different JSON outputs into one

My php server is generating two JSON output
1.] For MySql JSON printing I am using this code.
$sql = "select id ,Title , Meassage from lodhinews";
$result = $conn->query($sql);
$values = array();
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$values['data'][] = array(
'id'=>$row['id'],
'Title'=>$row['Title'],
'Meassage'=>$row['Meassage']
);
}
header('Content-Type: application/json;charset=utf-8');
echo json_encode($values ,JSON_PRETTY_PRINT);
} else {
$values = array(
'error'=>'No results found'
);
}
$conn->close();
?>
2.] For file name printing I am using this code
chdir('./uploads');
foreach(glob('*.*') as $filename){
$data[] = $filename;
}
echo json_encode($data);
?>
both the above code is working fine!
I wanted this both json output combined on one single page
not very complicated ! :)
$merged_array = array();
$merged_array[] = $data;
$merged_array[] = $values;
print json_encode($merged_array,JSON_PRETTY_PRINT);

Json array add onto php array

I want to acheive something simliar to this adding elements onto an array but when I use this methods two nodes get created in the json element. I only want one node with all the entires within that also can you name nodes ie Properties.
$json = array();
while($row = mysql_fetch_assoc($sth)) {
$json['name'] = $row['name'];
$json['id'] = $row['id'];
$data[] = $json;
}
$custom = array('name'=>'foo', 'id' => 'bar');
$data[] = $custom;
Try this code array_push is better option here,
<?php
$json = array();
while($row = mysql_fetch_assoc($sth)) {
$temp = array();
$temp = array('name' => $row['name'], 'id' => $row['id']);
array_push($json, $temp);
}
$custom = array('name'=>'foo', 'id' => 'bar');
array_push($json,$custom);
?>

PHP create nested array and pass back with json_encode

I have the following, and while $data['details'] is being populated OK, there should be three results in $data['tests'], but "tests" isn't showing at all in the JSON result:
{"details":["Clinical result","Signature result"]}
$data = array();
while ($row = mysql_fetch_array($result)) {
$data['details'] = array($row['tests_clinical'], $row['signature']);
foreach($row['lab_test_group_fk'] as $group){
$data['tests'] = array($group);
}
}
echo json_encode($data);
If I change the above to the following then I get only the last record for $row['lab_test_group_fk'], not all three records for that column (hence the foreach loop as above):
while ($row = mysql_fetch_array($result)) {
$data['details'] = array($row['tests_clinical'], $row['signature']);
$data['tests'] = array($row['lab_test_group_fk']);
}
echo json_encode($data);
{"details":["Clinical result","Signature result"],"tests":["21"]}
What am I doing wrong here?
Thanks to Tamil Selvin this was the solution that worked for me:
$data = array();
while ($row = mysql_fetch_array($result)) {
$data['details'] = array($row['tests_clinical'], $row['signature']);
$data['tests'][] = array($row['lab_test_group_fk']);
}
echo json_encode($data);
Which returned:
{"details":["Clinical result","Signature result"],"tests":[["31"],["2"],["21"]]}
Try
$data = array();
while ($row = mysql_fetch_array($result)) {
$data[]['details'] = array($row['tests_clinical'], $row['signature']);
$data[]['tests'] = array($row['lab_test_group_fk']);
}
echo json_encode($data);
or
while ($row = mysql_fetch_array($result)) {
$data[] = array(
'details' => array($row['tests_clinical'], $row['signature']),
'tests' => array($row['lab_test_group_fk'])
);
}
echo json_encode($data);
$data['tests'] = array($group); means reassign $data['tests'] to a new value again.
Try $data['tests'][] = array($group); .
You are overwriting existing data of $data. You need some kind of array where you will put all your records. Try this
$data = array();
while ($row = mysql_fetch_array($result)) {
$record = array(); // this creates new record
$record['details'] = array($row['tests_clinical'], $row['signature']);
foreach($row['lab_test_group_fk'] as $group){
$record['tests'] = array($group);
}
$data[] = $record; // this adds record to data
}
echo json_encode($data);

Dynamic data table creation for for column chart (columns and rows unknown)

I'm looking for a loop that retrieves the data from the MySQL result set with an unknown amount of columns and rows and puts it in GViz format.
With the following code I can read the data dynamically, but I can't get it into the format that Google Visualization API desires:
$cols = array();
$row = array();
$i = 0;
while ($i < mysql_num_fields($result)) {
$meta = mysql_fetch_field($result, $i);
if (!$meta) {
echo "No information available<br />\n";
}
$cols[]= "{id: '".$i."', label: '".$meta->name."', type: '".$meta->type."'}";
$i++;
}
while($r = mysql_fetch_assoc($result)) {
$row[]= $r;
}
$jsonTable = json_encode($cols);
$jsonTable2 = json_encode($row);
$Table3 = "{cols: {$jsonTable}, rows: $jsonTable2}";
echo $jsonTable;
echo '<br>';
echo $jsonTable2;
echo '<br>';
echo $Table3;
echo '<br>';
The JS error I get from the browser in debug-mode is:
Error: Invalid type, {[id= '0', label= 'mon', type= 'string']}, for column "0".
I have looked at the data parameter on googles documentation, but their data is hard coded as always. And this SO-page does not generate the cols and rows dynamically.
I'm glad for any help on getting the data parameter right. Thanks!
The cause of the error you see is that your JSON string construction is wrong. Don't try to build them yourself, it is much easier to build arrays in PHP and allow the json_encode function to take care of the hard parts for you.
You can parse your data from MySQL into a DataTable like this:
$data = array(
'cols' => array(),
'rows' => array()
);
for ($i = 0; $i < mysql_num_fields($result), $i++) {
$meta = mysql_fetch_field($result, $i);
if (!$meta) {
echo "No information available<br />\n";
}
$data['cols'][] = array(
'type' => ($i == 0) ? 'string' : 'number',
'label' => $meta->name,
'id' => $i
);
}
while($r = mysql_fetch_assoc($result)) {
$temp = array();
foreach ($data['cols'] as $col) {
$temp[] = array('v' => $r[$col['label']]);
}
$data['rows'][] = array('c' => $temp);
}
echo json_encode($data, JSON_NUMERIC_CHECK);

Convert SQL query to csv using odbc

I'm trying to get data from an off-site Miscrosoft SQL database using php's odbc connection, convert certain queries against it to arrays, and then turn those arrays into a csv that my cms can read and import. I'm able to succesfully conncect and return some results from the database, but my lack of php and SQL skills is killing me.
What I have right now, which is not much, but does what it's supposed to do:
$result = odbc_tables($connect);
$tables = array();
while (odbc_fetch_row($result))
{
if(odbc_result($result,"TABLE_TYPE")=="TABLE")
echo"<br>".odbc_result($result,"TABLE_NAME");
}
Is there any clear resource on the web on how to do what I want to do? The official php documentation seems to be about the most unhelpful documentation ever. A basic example: I want to return the entries here into csv format. I can get them in array format:
$query = "SELECT TOP 10 * FROM Communities";
$result = odbc_exec($connect, $query);
if ( $result )
{
while ( ($row = odbc_fetch_array($result)) )
{
print_r($row);
}
odbc_free_result($result);
}
else
{
echo 'Exec error: ' . odbc_errormsg();
}
odbc_close($conn);
Wish I had more, but I'm a bit lost on where to go next.
Using the tips, here's the working solution:
$theArray = array();
while ( ($row = odbc_fetch_array($result)) )
{
array_push($theArray, $row);
}
$header = array('Name', 'Hours', 'Fees', 'Notes', 'ShortDescription', 'URL');
$fp = fopen('array.csv', 'w');
fputcsv($fp, $header);
foreach ($theArray as $lines)
{
fputcsv($fp, $lines);
}
I just got done doing the exact project that you are asking about. I am running php 5.2 so you may be able to deal with the csv file more easily in a newer version. Here is my code:
<?php
// Uncomment this line for troubleshooting / if nothing displays
ini_set('display_errors', 'On');
$myServer = "GSRBI";
$myUser = "webuser";
$myPass = "Webuser1";
$myDB = "GSRBI";
$dbhandle = odbc_connect($myServer, $myUser, $myPass)
or die("Couldn't connect to SQL Server on $myServer");
$return = odbc_exec($dbhandle, 'select * from GSRBI.dbo.BounceBackEmail');
$subscribers_array = array();
$db_row = '';
$arrayrow = 0;
while ( $db_row = odbc_fetch_array($return) )
{
$arrayrow++;
$array[] = array(
'card_num' => $db_row['PlayerAccountNumber']
,'last_name' => ucfirst(strtolower($db_row['LastName']))
,'first_name' => ucfirst(strtolower($db_row['FirstName']))
,'email' => $db_row['EMailAddress']
,'earned_on_date' => date('m/d/Y', strtotime('-1 days'))
,'free_play' => $db_row['Offer1']
,'valid_through_date' => date('m/d/Y', strtotime('+15 days'))
);
}
echo print_r($arrayrow, true); ## display number of rows for sql array
echo " rows in ODBC ";
// Creates an array with GSR webteams contact info
$array1[] = array(
'card_num' => "123456789"
,'last_name' => "GSRwebteam"
,'first_name' => "GSRwebteam"
,'email' => "webteam#something.com"
,'earned_on_date' => date('m/d/Y', strtotime('-1 days'))
,'free_play' => "9"
,'valid_through_date' => date('m/d/Y', strtotime('+15 days'))
);
$result = array_merge((array)$array, (array)$array1); ## merge the two arrays together
// This will convert the array to csv format then save it
## Grab the first element to build the header
$arr = array_pop( $result );
$temp = array();
foreach( $arr as $key => $data )
{
$temp[] = $key;
}
$csv = implode( ',', $temp ) . "\n";
$csv .= to_csv_line( $arr ); ## Add the data from the first element
foreach( $result as $arr ) ## Add the data for the rest
{
$csv .= to_csv_line( $arr );
}
//echo print_r($csv, true); ## Uncomment to test output1
$f = fopen('reports/bounceback-'.date('m-d-Y').'.csv', "w");
fwrite($f, $csv);
fclose($f);
Echo "The report has ran";
return $csv;
function to_csv_line( $result )
{
$temp = array();
foreach( $result as $elt )
{
$temp[] = '' . addslashes( $elt ) . '';
}
$string = implode( ',', $temp ) . "\n";
return $string;
}

Categories