Google charts numbers - javascript

i use a google charts for getting data from google analytics to see it in my website
there is some data have a decimal number
how to make the charts forgot the number after the decimal.
I use a php foreach in the data generate for the charts
like this:
var data = google.visualization.arrayToDataTable([
['WEEK', 'total Cost' ,{ role: 'annotation' } ],
<? foreach($SOMETHING->getRows() as $row) {
$test = $row[2];
$test = number_format($test,0);?>
["<? echo $row[0]; ?>", <? echo $row[2]; ?>, <? echo $test; ?> ],
<? }?>
]);
i try the php coding "number_format" but it working in the script if i see the inspect of the page but not showing any charts in the page
if i put this code it work but the decimal is still there
var data = google.visualization.arrayToDataTable([
['WEEK', 'total Cost' ,{ role: 'annotation' } ],
<? foreach($tristanweekdata->getRows() as $row) { ?>
["<? echo $row[0]; ?>", <? echo $row[2]; ?>, <? echo $row[2]; ?> ],
<? }?>
]);
P.S.: this code is for one of my charts but its effect all the charts and all of them not showing anything
what should i do for remove the decimal????
thanks

Wrap your value in PHP's floor or intval method: (using number_format as you have it will add commas at the thousandths place in your numbers, so that should be avoided).
echo floor(456.8)."<br/>";
echo floor(456)."<br/>";
echo floor(456.1)."<br/>";
echo floor(456.0);
// outputs:
// 456
// 456
// 456
// 456
echo intval(456.8)."<br/>";
echo intval(456)."<br/>";
echo intval(456.1)."<br/>";
echo intval(456.0);
// outputs:
// 456
// 456
// 456
// 456
So in your example above:
$test = floor($row[2]);
//or
$test = intval($row[2]);
Floor:
Returns the next lowest integer value
http://php.net/manual/en/function.floor.php
Intval
Returns the integer value of var, using the specified base for the conversion (the default is base 10)
http://php.net/manual/en/function.intval.php

Related

Google Charts - Labels not matching data

I am building a statistical view for a client's booking system. They'd like to see which activities were booked in specific months.
I'm using Google Charts for this but the data doesn't match the labels being produced - i.e. the correct data is being attached to the wrong activity.
I've verified via the database and print_r's that the product IDs are being pulled from the database successfully and attached to the correct activity ID number, and that the number and order of labels matches the number and order of activities, which they are:
$sql = "SELECT ProductID, ProductName FROM products ORDER BY ProductID ASC";
$set = $link->query($sql);
while($row = $set->fetch_row())
{
$arrLabels[$row[0]] = "#".$row[0].": ".$row[1];
}
ksort($arrLabels);
$sql = "SELECT * FROM bookings_products INNER JOIN bookings ON bookings.BookingID=bookings_products.BookingProductBooking WHERE BookingConfirmed>0 ORDER BY BookingProductProduct ASC";
$set = $link->query($sql);
while($row = $set->fetch_array(MYSQLI_ASSOC))
{
$dm = substr($row['BookingDate'],5,2); // To get the month from YYYY-MM-DD dates
$arrPeople[$dm][$row['BookingProductProduct']] = $arrPeople[$dm][$row['BookingProductProduct']] + (1 * $row['BookingGroupSize']);
}
ksort($arrPeople);
echo "<pre>"; print_r($arrLabels); echo "</pre>";
echo "<hr/>";
echo "<pre>"; print_r($arrPeople); echo "</pre>";
I then build the Google Charts JS code like this:
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart()
{
var data = google.visualization.arrayToDataTable([
[<?php foreach($arrLabels as $p) { ?>'<?php echo str_replace("'","\'",$p); ?>', <?php } ?>{ role: 'annotation' } ],
['Jan', <?php foreach($arrLabels as $k=>$v) { ?><?php echo $arrPeople['01'][$k] ?: '0'; ?>, <?php } ?>],
['Feb', <?php foreach($arrLabels as $k=>$v) { ?><?php echo $arrPeople['02'][$k] ?: '0'; ?>, <?php } ?>],
['Mar', <?php foreach($arrLabels as $k=>$v) { ?><?php echo $arrPeople['03'][$k] ?: '0'; ?>, <?php } ?>],
['Apr', <?php foreach($arrLabels as $k=>$v) { ?><?php echo $arrPeople['04'][$k] ?: '0'; ?>, <?php } ?>],
['May', <?php foreach($arrLabels as $k=>$v) { ?><?php echo $arrPeople['05'][$k] ?: '0'; ?>, <?php } ?>],
['Jun', <?php foreach($arrLabels as $k=>$v) { ?><?php echo $arrPeople['06'][$k] ?: '0'; ?>, <?php } ?>],
['Jul', <?php foreach($arrLabels as $k=>$v) { ?><?php echo $arrPeople['07'][$k] ?: '0'; ?>, <?php } ?>],
['Aug', <?php foreach($arrLabels as $k=>$v) { ?><?php echo $arrPeople['08'][$k] ?: '0'; ?>, <?php } ?>],
['Sep', <?php foreach($arrLabels as $k=>$v) { ?><?php echo $arrPeople['09'][$k] ?: '0'; ?>, <?php } ?>],
['Oct', <?php foreach($arrLabels as $k=>$v) { ?><?php echo $arrPeople['10'][$k] ?: '0'; ?>, <?php } ?>],
['Nov', <?php foreach($arrLabels as $k=>$v) { ?><?php echo $arrPeople['11'][$k] ?: '0'; ?>, <?php } ?>],
['Dec', <?php foreach($arrLabels as $k=>$v) { ?><?php echo $arrPeople['12'][$k] ?: '0'; ?>, <?php } ?>],
]);
var options = {
title: 'Product popularity by month - Number of people (based on activity date)',
isStacked: true,
};
var chart = new google.visualization.BarChart(document.getElementById('chart3b'));
chart.draw(data, options);
}
</script>
<div id="chart3b" style="margin-top:15px; width: 900px; height: 500px; border:solid 1px #000;"></div><hr/>
You can see (via a static HTML copy-and-paste of the dynamic PHP output) the Google Chart produced here: http://www.stuart-pinfold.co.uk/stats.htm
You'll notice that activity #50 (Santa Experience) which had 195 visitors in December (month 12) is being assigned in the chart to activity #51 ("Zombie Air Rifle, Zombie Pistol, 10 Clay Shoots") instead.
Where am I going wrong?
Your first column of values is the month name, but your first cell at your headers row isn't a "month" label.
If you look at your example the activity #50 (Santa experience), you can see that the value of this label is 1 step to the left in the graph.
Make sure that instead of
['#5: Special Offer Ultimate Shooting Package ', '#6: CPSA Shotgun Skills Course',.....],
['Jan', 0,....
it looks like
['Months', '#5: Special Offer Ultimate Shooting Package ',.....],
['Jan', 0,.....
and everything should work just fine.

how to push arrays in array and NOT concatenate?

I have the following php code that gives an array variable called "markers".
window.markers = [];
<?php if( have_rows('actin_center') ): ?>
<?php while( have_rows('actin_center') ): the_row(); ?>
window.markers.push( [ ['<?php the_sub_field('center_name'); ?>', '<?php the_sub_field('center_address'); ?>', <?php the_sub_field('latitude'); ?>, <?php the_sub_field('longitude'); ?>] ] );
<?php endwhile; ?>
<?php endif; ?>
This works fine so far yet returns the array (on alert) as:
Cool center 1,Rewitz Gofella, 1234 Lorem,50,50,Cool center 2,Lorem Ipsum, 1234 Quosque,60,60,Cool center 3,Veniat elaborat, 1234 Ipsum,70,70
What I need, yet, is the following form keeping the arrays (of sub_fields) as they originally are inside the array and NOT concatenate them. As:
var markers = [
['First Center','First Address',50,50],
['Second Center','Second Address', -25.363882,131.044922],
['Third Center','Third Address', 10.363882,95],
['Fourth Center','Fourth Address', -50,-90],
['Fifth Center','Fifth Address', 30,5],
];
As you can see in the code above I tried with the simple double bracket [[ ]] but this doesn’t work.
How is this to be done correctly?
Thanks so much for help.
PS:
If someone feels urged to down vote my question, please be so kind to let me know why so I may learn something.
Due to comments:
alert( [[1,2][3,4]] ) will popup wrong 1,2,3,4
alert( JSON.stringify([[1,2][3,4]]) will popup [[1,2],[3,4]]
.push([1,2]) will add an array to markers: [[1,2],[3,4],[5,6]]
.push(1,2) will add elements to markers: [1,2,3,4,5,6]
But better way, is don't execute javascript .push (save client CPU time)
Define array in javascript in this way:
window.markers = [
<?php while( have_rows('actin_center') ): the_row(); ?>
["<?php the_sub_field('center_name');?>","<?php the_sub_field('center_address'); ?>",<?php the_sub_field('latitude');?>, <?php the_sub_field('longitude');?>],
<?php endwhile; ?>
];
result should looks like this
window.markers = [
['First Center', 'First Address', 50, 50],
['Second Center','Second Address',-25.363882, 131.044922],
[... ,... , ... ,...],
];

php code to get count from multiselect listbox and store in database

Below is my textbox values....i am unable to put my screen shots here..
i used multiple input tag jquery from this site..
http://loopj.com/jquery-tokeninput/demo.html
and second option of this demo. plz visit demo link ...
but i used multiple input textbox..in which we select multiple tags in one textbox okay.
like 700X 701X 702X
I need to get this textbox value and store in 3 rows..
FOR EX - in above screenshot there are 3 values 700,701,702 ok...now i need to ask you...when i click save i need to store this values in 3 different rows...
Rows No - used_receipt
1 700
2 701
3 702
i try like below but wont work...
textbox code
<input id="demo-input-local" type="text" value="<?php echo $data['used_receipt'];?>" name="used_receipt" />
javascript
<script type="text/javascript">
$(document).ready(function() {
$("#demo-input-local").tokenInput([
<?php
$receipt = $database->getRows("SELECT DISTINCT SM.receipt_no FROM scheme_master SM Inner join book_issue BI ON BI.book_no = SM.Book_no2 where SM.receipt_no not in (select used_receipt from book_return)");
foreach($receipt as $row){ ?>
{name: "<?php echo $row['receipt_no']; ?>"},
<?php } ?>
]);
});
</script>
php code to insert multiple values in database
$used_receipt = $_POST['used_receipt'];
$arr = explode(",", $used_receipt);
$max = count($arr);
for ($i = 0; $i < $max; $i++)
{
$insertrow = $database->insertRow("INSERT INTO book_return (book,surveyor,used_receipt,city,return_date,created)
VALUES (:book,:surveyor,:used_receipt,:city,:return_date,:created)",
array(':used_receipt'=>$arr[$i]);
}
Instead of
foreach($receipt as $row){ ?>
{name: "<?php echo $row['receipt_no']; ?>"},
<?php } ?>
Try this
$r = array();$i=1;
foreach($receipt as $row){
$r[]['name'] = $row['receipt_no'];$r[]['id'] = $i++;
}
echo "JSON.parse(\"".json_encode($t)."\")";
below is script which i used
<script type="text/javascript">
$(document).ready(function() {
$("#demo-input-local").tokenInput([<?php
$receipt = $database->getRows("SELECT DISTINCT SM.receipt_no FROM scheme_master SM Inner join book_issue BI ON BI.book_no = SM.Book_no2");
foreach($receipt as $row){ ?>
{id:<?php echo $row['receipt_no']; ?>,name: "<?php echo $row['receipt_no']; ?>"},
<?php } ?>
]);
});
</script>
and get this input in like
$used_receipt = $_POST['used_receipt'];
$arr = explode(",", rtrim($used_receipt));

Output php data into jquery array?

I'm creating a timeline using timesheet.js. The data will be input via custom fields in Wordpress. I want to be able to output that php data into the jquery array. Is that possible?
This is my php loop:
<?php if( have_rows('timeline') ):
while ( have_rows('timeline') ) : the_row();
echo the_sub_field('start_date');
echo the_sub_field('end_date');
echo the_sub_field('description');
echo the_sub_field('name');
endwhile;
endif; ?>
Here's the jquery, each time the php loops through I want it to output in the format:
<script type="text/javascript">
jQuery(function($) {
$(document).ready(function() {
new Timesheet('timesheet', 2002, 2013, [
['2002', '09/2002', 'A freaking awesome time', 'lorem'],
['06/2002', '09/2003', 'Some great memories', 'ipsum'],
['2003', 'Had very bad luck'],
['10/2003', '2006', 'At least had fun', 'dolor'],
['02/2005', '05/2006', 'Enjoyed those times as well', 'ipsum'],
['07/2005', '09/2005', 'Bad luck again', 'default'],
['10/2005', '2008', 'For a long time nothing happened', 'dolor'],
['01/2008', '05/2009', 'LOST Season #4', 'lorem'],
['01/2009', '05/2009', 'LOST Season #4', 'lorem'],
['02/2010', '05/2010', 'LOST Season #5', 'lorem'],
['09/2008', '06/2010', 'FRINGE #1 & #2', 'ipsum']
]);
});
});
</script>
It's quite simple to do this, really: just construct the array in php, and echo its json_encoded value:
<?php
$array = array();
if( have_rows('timeline') ) {
while ( have_rows('timeline') ) : the_row();
$array[] = array(
the_sub_field('start_date'),
the_sub_field('end_date'),
the_sub_field('description'),
the_sub_field('name')
);
endwhile;
echo '<script> var theArray = '.json_encode($array).';</script>';
} ?>
Job done, you now have a JS variable called theArray, and its value will be an array of arrays, containing all of the data you need to create new Timesheet('timesheet', 2002, 2013, theArray);
Yes, you need to echo <script> tags and you can generate any Javascript you want:
<?php
echo '<script>';
if( have_rows('timeline') ):
echo 'var foo = ['
while ( have_rows('timeline') ) : the_row();
echo '"'.the_sub_field('start_date').'",';
echo '"'.the_sub_field('end_date').'",';
echo '"'.the_sub_field('description').'",';
echo '"'.the_sub_field('name').'"';
endwhile;
echo '];';
endif;
echo '</script>';
?>

Javascript/jQuery Loop

I have a bit of jQuery that animates in some text then animates it out. The parameters of the animation are passed via PHP. I need the animation to loop but only after the animation is complete, but can't quite work it out.
<?php if ($text1_1 != "") { ?>
setTimeout(one_1,0); // From 0 to duration
setTimeout(one_2,<?php echo $duration * 2 ?>);
// From duration x2 to duration x3
<?php } ?>
<?php if ($text2_1 != "") { ?>
setTimeout(two_1,<?php echo $duration * 3 ?>); // From duration x3 to duration x4
setTimeout(two_2,<?php echo $duration * 5 ?>); // From duration x5 to duration x6
<?php } ?>
<?php if ($text1_1 != "") { ?>
function one_1() {
$('.text-1_1').animate({ <?php echo $animate1_1 ?>: '<?php echo $text1_1_end ?>' }, <?php echo $duration ?>, 'easeInOutCubic');
$('.text-1_2').animate({ <?php echo $animate1_2 ?>: '<?php echo $text1_2_end ?>' }, <?php echo $duration ?>, 'easeInOutCubic');
$('.text-1_3').animate({ <?php echo $animate1_3 ?>: '<?php echo $text1_3_end ?>' }, <?php echo $duration ?>, 'easeInOutCubic');
$('.text-1_4').animate({ <?php echo $animate1_4 ?>: '<?php echo $text1_4_end ?>' }, <?php echo $duration ?>, 'easeInOutCubic');
$('.text-1_5').animate({ <?php echo $animate1_5 ?>: '<?php echo $text1_5_end ?>' }, <?php echo $duration ?>, 'easeInOutCubic');
}
function one_2() {
$('.text-1_1').animate({ <?php echo $animate1_1 ?>: '<?php echo $text1_1_start ?>' }, <?php echo $duration ?>, 'easeInOutCubic');
$('.text-1_2').animate({ <?php echo $animate1_2 ?>: '<?php echo $text1_2_start ?>' }, <?php echo $duration ?>, 'easeInOutCubic');
$('.text-1_3').animate({ <?php echo $animate1_3 ?>: '<?php echo $text1_3_start ?>' }, <?php echo $duration ?>, 'easeInOutCubic');
$('.text-1_4').animate({ <?php echo $animate1_4 ?>: '<?php echo $text1_4_start ?>' }, <?php echo $duration ?>, 'easeInOutCubic');
$('.text-1_5').animate({ <?php echo $animate1_5 ?>: '<?php echo $text1_5_start ?>' }, <?php echo $duration ?>, 'easeInOutCubic');
}
<?php } ?>
How would you get function one_1() & function one_2() to loop after they've finished animating. There is also the possibility that there will be more similar functions.
Very sorry if this is a bit vague! having a bit of trouble explaining it.
Thanks for looking!
You can use the animate finish callback as described here:
http://api.jquery.com/animate/
$(element).animate( { animation params }, duration, function(){
// this is the animation finish callback
});
My suggestion is to use a recursive function, put the animation inside and call it recursively when the animation is finished
You could use something like this as a template. If the durations within each group are not the same, will require considerably more logic to set up and you would likely be best to provide all the animation data as an array, not echo to each animation
function one_1() {
/* use complete callback of one animation to call next function*/
$('.text-1_5').animate({ /* anim*/}, /*duration*/, /* easing*/, function(){
/* this animation is complete, call next function */
two_1();
});
/* other animations for this group*/
}
Maybe the solution is to replace setTimeout with
setInterval(two_1,<?php echo $duration; ?>);
setInterval(two_2,<?php echo $duration; ?>);
There is now need for doing $duration * 3 because your animations will start all in the same time

Categories