0

I have a spider-graph and it works perfectly with static data, not so great when I try import data from PHP.

what I got:

var d = [
          [
            {axis:"red",value:0.5},
            {axis:"blue",value:0.56},
            {axis:"yellow",value:0.42},
                  ]

There is a similar question here, but it doesn't work when I try to import data the following way:

var d = [
          [
            {axis:"red",value:<?php echo json_encode($php_variable1); ?>},
            {axis:"blue",value:<?php echo json_encode($php_variable2); ?>},
            {axis:"yellow",value:<?php echo json_encode($php_variable); ?>},
                  ]

Obviously, I'm not a professional. Any suggestions for the amateur?

Community
  • 1
  • 1
Martin
  • 33
  • 1
  • 4

1 Answers1

0

echo variables

Take this example, it's really simple.

<?php
$php_variable1 = 0.5;
$php_variable2 = 0.56;
$php_variable3 = 0.42;
?>
<script type="text/javascript">
    var d = [
        [
            { axis: "red", value: <?php echo $php_variable1; ?> },
            { axis: "blue", value: <?php echo $php_variable2; ?> },
            { axis: "yellow", value: <?php echo $php_variable3; ?> }
        ]
    ];
</script>

What happens here is that you are storing values in $php_variable1 to $php_variable2 and then are echoing the output inside JavaScript object.

json_encode array

The json_encode function will turn an array into a JSON object.

Using another example to demonstrate.

<?php
$php_variable1 = array("red" => 0.5);
$php_variable2 = array("blue" => 0.56);
$php_variable3 = array("yellow" => 0.42);
?>
<script type="text/javascript">
    var d = [
        [
            <?php echo json_encode($php_variable1); ?>,
            <?php echo json_encode($php_variable2); ?>,
            <?php echo json_encode($php_variable3); ?>
        ]
    ];
</script>

Alternatively, if you would prefer to not having to keep redefining variables you could shorten the above to as follows.

<?php
$myJSON = array(
    array("red" => 0.5),
    array("blue" => 0.56),
    array("yellow" => 0.42)
);
?>
<script type="text/javascript">
    var d = [
        [
            <?php echo json_encode($myJSON); ?>
        ]
    ];
</script>

This creates a multidimensional array which meaning that only one variable is created and json_encode iterates through it to create your object.

Panda
  • 6,955
  • 6
  • 40
  • 55
JustCarty
  • 3,839
  • 5
  • 31
  • 51