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.
Related
I have problems when trying to render correctly the Highcharts column range table. I have all the necessary data stored in PHP variables. The problem is that I can't get the table rendered when passing this variables.
If I try to pass direct numeric data, then the table is rendered, so the issue is in the data field.
Here's my code:
<?php
if (!isset($divId)) {
$mt = microtime();
$mt = explode(" ", $mt);
$divId = "stacked_container_" . floor($mt[0] * 100000) . "_" . $mt[1];
}
?>
<div id="<?php echo $divId; ?>" class="col-mx-12"></div>
<?php
$title = $elements['title'];
$resources = $elements['series']['resources'];
$values = $elements['series']['values'];
$resourcesSeries = '';
$valuesMinSeries = '';
$valuesMaxSeries = '';
foreach ($resources as $key => $resource) {
$resourcesSeries .= '"' . $resource . '",';
$valuesMinSeries .= $values[$key][0] . ',';
$valuesMaxSeries .= $values[$key][1] . ',';
}
$globalNav = $view['nav'];
// Transforming strings into array type
$valuesMin = str_split($valuesMinSeries);
$valuesMax = str_split($valuesMaxSeries);
$globalNav->addScriptJS("
$(document).ready(function () {
$('#" . $divId . "').highcharts({
chart: {
type: 'columnrange'
},
title: {
text: '" . $title . "'
},
xAxis: {
categories: [" . $resourcesSeries . "]
},
yAxis: {
title: {
text: 'range'
}
},
series: [{
data: [
[<?php echo $valuesMin[0]?> , <?php echo $valuesMax[0]?> ]
]
}]
});
});
");
?>
In this example I'm trying to display only the first element of $valuesMin and $valuesMax.
The final aim is to render all the data, so I need to implement a foreach too.
You appear to be duplicating your resources array, by calling it as both your $resources variable, and your $values variable:
$resources = $elements['series']['resources'];
$values = $elements['series']['resources'];
Which I will assume should be something like:
$resources = $elements['series']['resources'];
$values = $elements['series']['values'];
I have found a solution to the problem. This is how:
//The result will be in the $data variable
$data = '';
foreach ($resources as $key => $resource) {
$resourcesSeries .= '"' . $resource . '",';
$valuesMinSeries .= $values[$key][0] . ',';
$valuesMaxSeries .= $values[$key][1] . ',';
$data .= "[".values[$key][0]. "," .$values[$key][1]. "],";
}
And in the series field:
series: [{
data: [ " .$data. " ]
}]
Hope this will help!
I am trying to set location markers. The code below is not looping through the results and displays only the first row. I tested the query and result outside of Google Maps and it work.
var addresses = [
<?php
while($row = mysql_fetch_array($results)) {
echo '"'.$row['company'].', '. $row['address'].', ' . $row['city'] . ', ' . $row['state'] . ', ' . $row['zip'] .'",';
}
?>
];
This is what you should do:
<?php
...
$array = array();
while ($row = mysql_fetch_assoc($results)) {
$array[] = array(
'company'=>$row['company'],
'address'=>$row['address'],
'lat'=>$row['latitude'],
'lng'=>$row['longitude'],
); // add what ever cels you need
}
$json_string = json_encode($array);
echo 'var addresses=' . $json_string . ';';
...
?>
If you keep having problems, please post the javascript part of the code; this is just the part where you print an object (or array) in a format that javascript can read.
I am trying to use $value inside the $feed_title variable. And generate all 200 $feed_title variables.
What I am trying to accomplish would look like this:
Feed Url: http://something.com/term/###/feed
Feed Title: Some Title
Where the ### varies from 100-300.
I am using the following code, and getting the urls, but not sure how to get the titles for each feed:
$arr = range(100,300);
foreach($arr as $key=>$value)
{
unset($arr[$key + 1]);
$feed_title = simplexml_load_file('http://www.something.com/term/'
. ??? . '/0/feed');
echo 'Feed URL: <a href="http://www.something.com/term/' . $value
. '/0/feed">http://www.something.com//term/' . $value
. '/0/feed</a><br/> Feed Category: ' . $feed_title->channel[0]->title
. '<br/>';
}
Do I need another loop inside of the foreach? Any help is appreciated.
If you want to get the title of a page, use this function:
function getTitle($Url){
$str = file_get_contents($Url);
if(strlen($str)>0){
preg_match("/\<title\>(.*)\<\/title\>/",$str,$title);
return $title[1];
}
}
Here's some sample code:
<?php
function getTitle($Url){
$str = file_get_contents($Url);
if(strlen($str)>0){
preg_match("/\<title\>(.*)\<\/title\>/",$str,$title);
return $title[1];
}
}
$arr = range(300,305);
foreach($arr as $value)
{
$feed_title = getTitle('http://www.translate.com/portuguese/feed/' . $value);
echo 'Feed URL: http://www.translate.com/portuguese/feed/' . $value . '<br/>
Feed Category: ' . $feed_title . '<br/>';
}
?>
This gets the title from translate.com pages. I just limited the number of pages for faster execution.
Just change the getTitle to your function if you want to get the title from xml.
Instead of using an array created with range, use a for loop as follows:
for($i = 100; $i <= 300; $i++){
$feed = simplexml_load_file('http://www.something.com/term/' . $i . '/0/feed');
echo 'Feed URL: http://www.something.com/term/' . $i . '/0/feed/ <br /> Feed category: ' . $feed->channel[0]->title . '<br/>';
}
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
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);