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],
[... ,... , ... ,...],
];
Related
I'm not sure how to search this, but I have an array in php numbered 1 to 20. I have a foreach loop to output the values and have the user be able to click on the numbers. After clicking the number, the page would then output the number clicked.
HTML:
<div id="chapters" onclick="getChapter()">
$array = range(1,20);
foreach($array as $chapter) {
?>
<p class="getChapter" id="currChapter">Chapter <?php echo $chapter;?></p>
<?php
}
?>
</div>
Javascript
function getChapter() {
chapter = document.getElementById("currChapter").id;
document.write(chapter);
}
I'm not able to output the number that the user clicks on.
I have tried putting
id=<?php $chapter?>
, but that does not work as well as replacing id with value and name.
I would recommend passing the $chapter as parameter of a function "Onclick" event :
<div id="chapters">
<?php
$array = range(1,20);
foreach($array as $chapter) {
?>
<p class="getChapter" onClick="getChapter(<?php echo $chapter;?>)">Chapter <?php echo $chapter;?></p>
<?php
}
?>
and the Javascript:
function getChapter(chapterNumber) {
alert(chapterNumber);
}
I don't really understand what you want to do, seems you explanation just a example, but may be this will help. You can call function getChapter with parameter ( onClick="getChapter(<?php echo $chapter;?>) ) :
$array = range(1,20);
foreach($array as $chapter) {
?>
<p class="getChapter" id="currChapter" onClick="getChapter(<?php echo $chapter;?>)">Chapter <?php echo $chapter;?></p>
<?php
}
function getChapter(chapter) {
document.write(chapter);
}
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
I'm trying to print out an array of dates pulled from an API, which come out formatted as YYYYmmdd, i.e. 20160701. When I convert them to a friendlier format and then go to print them in Highcharts, it actually will do a mathematical calculation based on the operator being used to separate the date elements. Obviously that's not what I want it to do. So the first date is actually performing 7 minus 1 minus 2016, resulting in the -2010. Does anyone know what is causing this?
PHP Snippet
foreach ($arr['rows'] as $item){
$dates[] = DateTime::createFromFormat('Ymd', $item[0])->format('m-d- Y');
}
Javascript Highchart Plugin
$('#myChart').highcharts({
xAxis: {
categories: [
<?php
echo implode(',', $dates);
?>
]
},
What the dates end up looking like:
The problem is that you're not injecting any quotes in the Javascript source.
What you get is something like:
$('#myChart').highcharts({
xAxis: {
categories: [ 7-1-2016 ] // <--- should be [ "7-1-2016" ]
}
});
which is evaluated as categories: [ -2010 ] on the Javascript side.
You should do:
$('#myChart').highcharts({
xAxis: {
categories: [
<?php
echo '"'.implode('","', $dates).'"';
?>
]
}
});
Or if you prefer to have this fixed in the PHP code that is building this array:
foreach ($arr['rows'] as $item){
$dates[] = DateTime::createFromFormat('Ymd', $item[0])->format('"m-d-Y"');
}
EDIT: as suggested by jlbriggs, a better approach would be to use json_encode().
At least on $dates ...
$('#myChart').highcharts({
xAxis: {
categories: <?php echo json_encode($dates); ?>
}
});
... or on the whole object passed to highcharts() (assuming it's entirely built on the PHP side):
$('#myChart').highcharts(<?php echo json_encode($highChartsObject); ?>);
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>';
?>
Answer from here : https://stackoverflow.com/a/12863675/894470 is how to assign array to variable.
I'm getting my data from php but when I echo it inside javscript like example below my chart wont draw.
var month_data= [<?php echo json_encode($lol); ?>];
but I can show alert and see all my data no problem like below:
If I copy the text from alert and paste it in array like below:
var month_data= [{month: '2014-01', KFC: 0, PizzaHut: 1},{month: '2014-03', KFC: 2, PizzaHut: 1},{month: '2014-04', KFC: 1, PizzaHut: 0},{month: '2014-05', KFC: 0, PizzaHut: 1},{month: '2014-07', KFC: 1, PizzaHut: 0},{month: '2014-10', KFC: 42, PizzaHut: 42}];
my chart will draw. What is wrong here??
UPDATE: My query:
$lol = array();
while ($row = mysqli_fetch_array($result)) {
$lol[] = "{month: '". $row['year'] ."-". $row['month'] ."', KFC: ". $row['kfc'] .", PizzaHut: ". $row['pizzahut'] ."}";
}
and I'm using Morris.js: http://morrisjs.github.io/morris.js/ to generate my chart.
You need a real PHP structure to encode it into JSON, not just a string:
$lol = array();
while ($row = mysqli_fetch_array($result)) {
$lol[] = Array(
"month" => $row['year'].'-'.$row['month'],
"KFC" => $row['kfc'],
"PizzaHut" => $row['pizzahut']
);
}
and:
var month_data = <?php echo json_encode($lol); ?>;
json_encode will automatically translate $lol into a json array containing objects (associative arrays are translated into objects).
All is fine, you just have to parse it to json format, you can do that using:
var month_data= JSON.parse('<?php echo json_encode($lol); ?>');
edit your php code like this:
$lol[] = array("month" => $row['year'], "KFC" => $row['kfc'] ...
anyway i do not recommend using php in js, the better way would be to put the content from the variable somewhere in html and than to take it with js.