简体   繁体   中英

Quoting PHP Variable inside PHP Variable for Javascript Donut Chart

I'm having a bit of a difficult time today with passing some PHP variables over to Javascript for a Donut chart. I've been messing with this for a good while now and haven't been able to figure it out yet, I've checked through posts on here as well as numerous google searches but haven't been able to find the answer yet. Here's what I'm trying to accomplish:

I'm trying to push data from MySQL to a Javascript Donut chart for web referrers to a specific PHP page. The syntax for the Javascript chart is as such:

<script>
Morris.Donut({
element: 'css div',
data: 
[
{ label: '<?php echo($graph["referrer"]); ?>', value: '<?php echo($graph["chart"]); ?>' },
] 
});
</script>

The $graph['referrer'] variable holds a referrer name such as "Google.com", and the $graph['count'] variable holds the corresponding record count for the referrer name as a number, such as "5".

The Javascript line that starts with "{label" denotes one part of the Donut chart. Initially the data pulled from MySQL is done so with fetchArray(), what I am trying to do is to generate each "{label" line using a PHP foreach statement (eg. foreach($Array as $graph)) so that the graph can be generated dynamically based on the number of referrer names returned by fetchArray(). I've tried pretty much everything I can think of to make this work - storing the entire Javascript line in PHP and then echoing it out to Javascript, etc. But it always causes an internal error with PHP.

I'm sure the answer is right under my nose, thank you all for your time.

Use json_encode() to generate a clean data object:

in PHP:

$data = array( array( 'label' => $graph["referrer"] ), 'value' => $graph["chart"] ) );

in your JavaScript;

data: <?php echo json_encode($data); ?>

The proper way of passing arrays of php variables to js scripts is using json . Here's what you need to do:

php part:

$sql = 'select * from ....';    // your query
// execute query
// as I don't know what mysql api do you use, 
// it's kinda pseudo-code
// but the main idea is to get all rows 
// you need in one array `$graphs`

$graphs = array();
while ($graph = fetch_array()) {
    $graphs[] = array(
        'label' => $graph["referrer"],
        'value' => $graph["chart"],
    );
}

js part:

<script>
Morris.Donut({
    element: 'css div',
    data: <?php echo json_encode($graphs); ?>
});
</script>

You are not at all looping the $graph variables. It just has only one:

<script>
  Morris.Donut({
    element: 'css div',
    data: [{
      label: '<?php echo($graph["referrer"]); ?>',
      value: '<?php echo($graph["chart"]); ?>'
    },]
  });
</script>

The above code will render only one variable. I believe, you should have some kind of looping here:

<script>
  Morris.Donut({
    element: 'css div',
    data: [
<?php foreach (/* some loop */) { ?>
      {
        label: '<?php echo($graph["referrer"]); ?>',
        value: '<?php echo($graph["chart"]); ?>'
      },
<?php } ?>
    ]
  });
</script>

Or the best way is to use an array and json_encode() to output the JSON.

My final solution was to concatenate the string together in a big, ugly but working glob.

<script>
Morris.Donut({
element: 'graph div'
data: {
<?php foreach($multidimarray as $graph): ?>
    <?php echo htmlspecialchars("{label: "."'".$graph['referrer']."'".", value: "."'".$graph['count']."'"." }, "); ?>
<?php endforeach; ?>
]
});
</script>

Which returns as: { label: 'Facebook', value: '2' }, { label: 'Direct', value: '2' }, { label: 'Microsoft', value: '1' }, { label: 'Ask.com', value: '1' }, { label: 'Google', value: '1' },

Again thank you all for your help, even though I didn't understand them I appreciate all of your answers. I will mark Gerald's answer because he responded first, mentioned json_encode first, and got me closest to the desired outcome.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM