I am implementing Highcharts in my application. It needs data in specific format.
The data in my table is as follows
The javascript needs data in below format
When I var_dump my x_axis array and y_axis array, I get below result
Which php functions should I use to format my array elements and pass to that JavaScript in that format?
data:[
[<? echo PHP_some_function(" ' ", x_axis) ?>, <? echo (y_axis) ?>] //quotes for x, no quotes for y value
] //Moreover it should run for all the values in x_axis and y_axis
I need some logic here..
My final graph would look like
The problem is your query.
It should be like the following.
SELECT x_axis, y_axis FROM yourTableName;
This way you'll get exactly the format that Highcharts needs. You just have to insert it inside an array.
Assuming:
$x_axis = array('Safari', 'Opera', 'Firefox', 'IE', 'Chrome', 'Others');
$y_axis = array(10, 6, 40.5, 20, 10.6, 0.5);
This should work:
$data = array();
$length = count($x_axis);
for ($i = 0; $i < $length; $i++) {
$data[] = array($x_axis[i], $y_axis[i]);
}
[<? echo "'". json_encode($x_axis). "', " . json_encode($y_axis) ?>]
Demo: http://codepad.org/G5JAtXWu
Nix that I was confused.
What you want to do is this:
foreach($x_axis as $key=>$x) {
echo "['" . $x . "', " . $y_axis[$key] . "]";
}
Demo: http://codepad.org/SKNk1VaX
To wrap it all up:
$d = array();
foreach($x_axis as $key=>$x) {
$d[] = "['" . $x . "', " . $y_axis[$key] . "]";
}
echo json_encode($d);
Demo: http://codepad.org/KhofwXCi
probably array combine and than json encode and replace? just in case for diversity;)
<?php
$x_axis = array(
'Safari', 'Opera', 'fireFox'
);
$y_axis = array(
10, 30.4, 50
);
$keyFilled = array_combine($x_axis, $y_axis);
arsort($keyFilled);
$jsonData = json_encode($keyFilled);
$jsonDataReplaced = str_replace(array(',', '{', '}', ':'), array('],[', '[', ']', ','), $jsonData);
echo '<pre>';
var_dump('['.$jsonDataReplaced.']');
?>
output is:
string(45) "[["fireFox",50],["Opera",30.4],["Safari",10]]"
http://phpfiddle.org/main/code/jq4-cgb
Related
I have this string:
[25-03-15, 1236], [26-03-15, 3000], [27-03-15, 3054], [30-03-15, 4000]
I want to get two parts from it as below:
['25-03-15','26-03-15','27-03-15','30-03-2015']
and
[1236,3000,3054,4000]
Please guide me how I can perform this task.
PS: I am working of view page of codeigniter.
I'm getting the first thing as:
<?php
$usd=$this->db->query('select transaction_date, SUM(amount) as total
from transactions GROUP BY transaction_date')->result_array();
$str = '';
for($i=0; $i<count($usd); $i++){
if($i!=0){
$str = $str.', ['.date('d-m-y', strtotime($usd[$i]["transaction_date"])).', '.$usd[$i]["total"].']';
}else{
$str = $str.'['.date('d-m-y', strtotime($usd[$i]["transaction_date"])).', '.$usd[$i]["total"].']';
}
}
echo $str;
?>
Try this..
$date = '';
$total = '';
for($i=0; $i<count($usd); $i++){
if($i!=0){
$date .= date('d-m-y', strtotime($usd[$i]["transaction_date"])).', ';
$total .= $usd[$i]["total"].', ';
}else{
$date .= date('d-m-y', strtotime($usd[$i]["transaction_date"])).', ';
$total .= $usd[$i]["total"].', ';
}
}
echo $finaldate='['. $date.']';
echo $finaltotal='['. $total.']';
I don't see any reason why you need to save this data from your db in a string. Just save it in an array and it is that easy:
So here I save your data in an array, so that you get this structure:
array(
array(25-03-15, 1236),
array(26-03-15, 3000),
array(27-03-15, 3054),
array(30-03-15, 4000)
)
The you can simply use array_column() to extract the single columns, like this:
<?php
$usd = $this->db->query('select transaction_date, SUM(amount) as total
from transactions GROUP BY transaction_date')->result_array();
foreach($usd as $k => $v)
$result[] = [date('d-m-y', strtotime($usd[$k]["transaction_date"])), $usd[$k]["total"]];
$partOne = array_column($result, 0);
$partTwo = array_column($result, 1);
?>
Also if you then need this data in a string as you said in the comments you can simply transform it:
I will pass this extracted data to a graph that accepts this kind of data – Shahid Rafiq 6 mins ago
Just use this:
echo $str = "[" . implode("],[", array_map(function($v){
return implode(",", $v);
}, $usd)) . "]";
output:
[25-03-15, 1236], [26-03-15, 3000], [27-03-15, 3054], [30-03-15, 4000]
EDIT:
If you also want the parts as string just simply do this:
$partOne = "[" . implode("],[", array_column($arr, 0)) . "]";
$partTwo = "[" . implode("],[", array_column($arr, 1)) . "]";
output:
[25-03-15],[26-03-15],[27-03-15],[30-03-15]
[1236],[3000],[3054],[4000]
I'm trying to store the numbers from the strings on:
http://driftsdata.statnett.no//snpsrestapi/PowerData/PowerOverview/se?callback=Production.UpdateData
To my database, as these varies every hour.
However, preg_replace and str_replace doesnt work for me, as it only prints out "22" instead of "22 340" as it sais on the website.
here is my code:
for($i=0; $i<6; $i++) {
$info = get_data($countries[$i], $text);
for($j=0; $j<8; $j++) {
$info[$j] = preg_replace('/\s+/', '', $info[$j]);
$info[$j] = (int)$info[$j];
any help?
Since you are dealing with json format, the cleanest and safest way is to use json_decode():
<pre>
<?php
$jsontext = preg_replace('~^[^(]*+\(|\)$~', '', $text);
$json = json_decode($jsontext);
foreach($json->production as $prod) {
printf("<br/><strong>%s</strong><br/>%s\t%s\t%s\t%s\t%s",
$prod->type, $prod->se, $prod->dk, $prod->no, $prod->fi, $prod->ee);
$result[$prod->type] = preg_replace('~[ -]~', '',
array($prod->se, $prod->dk, $prod->no, $prod->fi, $prod->ee));
}
echo '<br/>' . print_r($result, true);
?>
</pre>
I'm trying to populate a Flot chart with data from a MySQL query in PHP. I'm sure this is a crappy way to go about things (without Ajax or JSON, neither of which I'm comfortable with yet), but I output the query results in the format Flot needs for its data points into a hidden div on my PHP page, like so:
function get_team_chart($arr) {
$data1 = array();
$data2 = array();
foreach ($arr as $a) {
$data1[] = '[' . $a['week'] . ',' . $a['pts'] . ']';
$data2[] = '[' . $a['week'] . ',' . $a['league_avg'] . ']';
}
$str1 = implode(', ', $data1);
$str2 = implode(', ', $data2);
echo " <div id='series1' style='display:none;'>" . $str1 . "</div>
<div id='series2' style='display:none;'>" . $str2 . "</div>";
}
Then I try to pull that data into my chart in JavaScript like so:
function plot_team_chart() {
var series1 = $('#series1').html();
var series2 = $('#series2').html();
$.plot( $("#team-chart"),
[ series1,
series2],
{ xaxis: {min:0,
max:13},
yaxis: {max:150,
min:0}}
);
}
This doesn't throw any JS errors at runtime, and the chart shows up with the specified mins and maxes, but no data is plotted. I checked the values of series1 and series2 and they are both without quotes around the numerical values (i.e. they are like [1,120.3], [2,89.0], not like ["1","120.3"], ["2","89.0"]).
This is my first foray into the world of Flot, so please be gentle. Also, I verified that the chart plots fine with hardcoded values.
Thank you.
Got it working. Feel free to respond with how this functionality would be accomplished with Ajax and/or JSON, but here is how I accomplished pulling in data within a hidden div to plot on Flot:
function plot_team_chart() {
var tmp1 = new Array();
var tmp2 = new Array();
var tmp3 = new Array();
var data = new Array();
$('.to-plot').each(function() {
tmp1 = $(this).html().split('|');
for (var i=0; i<tmp1.length; i++) {
tmp2 = tmp1[i].split(',');
tmp3.push(tmp2);
}
data.push({ label: $(this).attr('data_label'),
data: tmp3});
tmp3 = [];
});
var options = { xaxis: { min:1,
max:13},
yaxis: { max:120,
min:30},
grid: { borderColor:'#ccc'},
legend: { show:true,
position:'se'}};
if (data.length > 0) {
$.plot( $("#team-chart"),
data,
options
);
}
}
And the modified PHP to accommodate the changes:
function get_team_chart($arr) {
$data1 = array();
$data2 = array();
foreach ($arr as $a) {
$data1[] = $a["week"] . "," . $a["pts"];
$data2[] = $a["week"] . "," . $a["league_avg"];
}
$str1 = implode('|', $data1);
$str2 = implode('|', $data2);
echo " <div id='series1' data_label='avg score' style='display:none;'>" . $str1 . "</div>
<div id='series2' data_label='league avg' style='display:none;'>" . $str2 . "</div>";
}
If you just want quotes around those variables, why not do:
$data1[] = '["' . $a['week'] . '","' . $a['pts'] . '"]';
$data2[] = '["' . $a['week'] . '","' . $a['league_avg'] . '"]';
That will quote your output via the lazy man's way.
I'm using a javascript plugin this is the line which I need help from u
<script type="text/javascript">
$('ul#news').newswidget({ source: ['http://rss.news.yahoo.com/rss/us', 'http://rss.news.yahoo.com/rss/world', 'http://feeds.bbci.co.uk/news/rss.xml'],
I would like to add URL data from MySQL
I'm using it with while loop like this
$('ul#news').newswidget({ source:[<?php
while($rssrow = mysql_fetch_array($rss))
{
echo "'"."$rssrow[rss_name]"."'".",";
}
?>],
It doesn't work properly :(.
I need to get like URL,URL,RUL like this.
that means no comma for the last one
any one please help me
You can actually do that pretty easily by a simple reorganization:
if($rssrow = mysql_fetch_array($rss))
{
echo "'".$rssrow['rss_name']."'";
while($rssrow = mysql_fetch_array($rss))
{
// note no quotes -- they are redundant
// prepend the comma
echo ","."'".$rssrow['rss_name']."'";
}
}
It does make for an extra step for the reader, but it does have the benefit of not needing substring, a new array, or a flag.
You could just build the string and remove the last comma:
$result = '';
while($rssrow = mysql_fetch_array($rss))
{
$result .= "'"."$rssrow[rss_name]"."'".",";
}
echo ($result != '') ? substr($result, 0, -1) : "''";
OR use implode():
$result = array();
while($rssrow = mysql_fetch_array($rss))
{
$result[] = $rssrow[rss_name];
}
echo "'" . implode($result, "','") . "'";
(both of these methods will output '' if the result set is empty.)
$urls = "";
while($rssrow = mysql_fetch_array($rss))
{
$urls.= "'$rssrow[rss_name]',";
}
echo substr($urls, 0, -1);
I wonder why no comment points out that you should definitely escape your output. If an entry contains a ', all solutions aside from Dmitry F’s first will break badly.
$('ul#news').newswidget({ source:[<?php
$arr = array();
while($rssrow = mysql_fetch_array($rss))
{
$arr[] = '"' . str_replace('"', '\"', $rssrow['rss_name']) . '"';
}
echo implode(',', $arr);
?>],
here is a little bit different approach:
<?php
$news = array(
'source' => array(
'http://example.com',
'http://example.com'
)
);
$news_json = json_encode($news);
?>
<script>
$('ul#news').newswidget(<?php echo $news_json; ?>);
</script>
another variation:
$url = array();
while($rssrow = mysql_fetch_array($rss))
{
$url[] = '"' . $rssrow['rss_name'] . '"';
}
echo implode(',', $url);
I need to convert a CSV file to JSON on the server using PHP. I am using this script which works:
function csvToJSON($csv) {
$rows = explode("\n", $csv);
$i = 0;
$len = count($rows);
$json = "{\n" . ' "data" : [';
foreach ($rows as $row) {
$cols = explode(',', $row);
$json .= "\n {\n";
$json .= ' "var0" : "' . $cols[0] . "\",\n";
$json .= ' "var1" : "' . $cols[1] . "\",\n";
$json .= ' "var2" : "' . $cols[2] . "\",\n";
$json .= ' "var3" : "' . $cols[3] . "\",\n";
$json .= ' "var4" : "' . $cols[4] . "\",\n";
$json .= ' "var5" : "' . $cols[5] . "\",\n";
$json .= ' "var6" : "' . $cols[6] . "\",\n";
$json .= ' "var7" : "' . $cols[7] . "\",\n";
$json .= ' "var8" : "' . $cols[8] . "\",\n";
$json .= ' "var9" : "' . $cols[9] . "\",\n";
$json .= ' "var10" : "' . $cols[10] . '"';
$json .= "\n }";
if ($i !== $len - 1) {
$json .= ',';
}
$i++;
}
$json .= "\n ]\n}";
return $json;
}
$json = csvToJSON($csv);
$json = preg_replace('/[ \n]/', '', $json);
header('Content-Type: text/plain');
header('Cache-Control: no-cache');
echo $json;
The $csv variable is a string resulting from a cURL request which returns the CSV content.
I am sure this is not the most efficient PHP code to do it because I am a beginner developer and my knowledge of PHP is low. Is there a better, more efficient way to convert CSV to JSON using PHP?
Thanks in advance.
Note. I am aware that I am adding whitespace and then removing it, I do this so I can have the option to return "readable" JSON by removing the line $json = preg_replace('/[ \n]/', '', $json); for testing purposes.
Edit. Thanks for your replies, based on them the new code is like this:
function csvToJson($csv) {
$rows = explode("\n", trim($csv));
$csvarr = array_map(function ($row) {
$keys = array('var0','var1','var2','var3','var4','var5','var6','var7','var8','var9','var10');
return array_combine($keys, str_getcsv($row));
}, $rows);
$json = json_encode($csvarr);
return $json;
}
$json = csvToJson($csv);
header('Content-Type: application/json');
header('Cache-Control: no-cache');
echo $json;
Well there is the json_encode() function, which you should use rather than building up the JSON output yourself. And there is also a function str_getcsv() for parsing CSV:
$array = array_map("str_getcsv", explode("\n", $csv));
print json_encode($array);
You must however adapt the $array if you want the JSON output to hold named fields.
I modified the answer in the question to use the first line of the CSV for the array keys. This has the advantage of not having to hard-code the keys in the function allowing it to work for any CSV with column headers and any number of columns.
Here is my modified version:
function csvToJson($csv) {
$rows = explode("\n", trim($csv));
$data = array_slice($rows, 1);
$keys = array_fill(0, count($data), $rows[0]);
$json = array_map(function ($row, $key) {
return array_combine(str_getcsv($key), str_getcsv($row));
}, $data, $keys);
return json_encode($json);
}
None of these answers work with multiline cells, because they all assume a row ends with '\n'. The builtin fgetcsv function understands that multiline cells are enclosed in " so it doesn't run into the same problem. The code below instead of relying on '\n' to find each row of a csv lets fgetcsv go row by row and prep our output.
function csv_to_json($file){
$columns = fgetcsv($file); // first lets get the keys.
$output = array(); // we will build out an array of arrays here.
while(!feof($file)){ // until we get to the end of file, we'll pull in a new line
$line = fgetcsv($file); // gets the next line
$lineObject = array(); // we build out each line with our $columns keys
foreach($columns as $key => $value){
$lineObject[$value] = $line[$key];
}
array_push($output, $lineObject);
}
return json_encode($output); // encode it as json before sending it back
}
Some tips...
If you have URL opening enabled for fopen() and wrappers, you can use fgetscsv().
You can build an array of the CSV, and then convert it with PHP's native json_encode().
The correct mime type for JSON is application/json.
You could probably reduce the overhead by removing all the spaces and \n's. But that's in your note.
You could increase the performance by skipping the preg_replace and passing a boolean that would turn it on and off.
Other than that, the variable unrolling of your var[1-10] actually is good, as long as there are always ten varaibles.
The explode and the foreach approach are just fine.
I recommend using Coseva (a csv parsing library) and using the built in toJSON() method.
<?php
// load
require('../src/CSV.php');
// read
$csv = new Coseva\CSV('path/to/my_csv.csv');
// parse
$csv->parse();
// disco
echo $csv->toJSON();