简体   繁体   中英

PHP JSON_encode output not as expected

Hello I have a PHP script that pulls info from a database table.

The table structure is :

Delaytype(varchar)| Delayhours(int)

The PHP script groups by delay type.

<!doctype html>
<?php

?>
<head>

    <script src="chartjs/Chart.js-master/Chart.js"></script>
    <script src="chartjs/Chart.js-master/Chart.min.js"></script>
    <script src="chartjs/Chart.js-master/package.json"></script>
</head>



<body>
    <?php
include "config.php";

// Check connection
if (mysqli_connect_errno($con))
{
echo "Failed to connect to DataBase: " . mysqli_connect_error();
}
else
{


$result = mysqli_query($con, "SELECT Delaytype, COUNT(1) as cnt FROM    
delays GROUP BY Delaytype; ");
echo "<table id='mytable'><th>Delay Type</th><th>Delay Hours</th>";
$pieData = array();

 while($row = mysqli_fetch_array($result))
 {   
   $pieData[] = array('value' =>$row['cnt'], 'color' =>'#878BB6 ');

    }
?>

<script>
 var pieData = <?php echo" ".json_encode($pieData).""; ?>;//problem



          // pie chart options
    var pieOptions = {
         segmentShowStroke : false,
         animateScale : true
    };
    // get pie chart canvas
    var countries= document.getElementById("buy").getContext("2d");
    // draw pie chart
    new Chart(countries).Pie(pieData, pieOptions);

    </script>
 </body>
</html>
<?php
mysqli_close($con);     

}

?>

I am trying to output the JSON in the following format - The example below works with just the entered values. Its Javascript to creat a pie chart with chart js.

It expects the JSON like

 [{value:?,color:"?"},{value:?,color:"?"}]

When I echo my JSON I get

     [{"value":"?",color:"?"}],[{"value":?,color:"?"},{"value":?,color:"?"}]

The first set is a duplicate of the second and then it works?. Is there a better way of doing this? With the above code I get part of a chart. The other issue is I have to get a different color for each row?currently it is the same color as I do not know how I can get different colors in as it is not part of my database structure?

The below example works to create the chart not using the database. So ideally I would like some advice on 1) how to get the JSON out of my database to fit in the below format. 2) Is there a way without storing colors in a database table where I can apply different color values to the below

var pieData =  [
        {
            value: 20 , // ideal :I want database data
            color:"#878BB6"//color that I have chosen  

       },
        {
            value : 40,
            color : "#4ACAB4"

        },
        {
            value : 10,
            color : "#FF8153"

        },
        {
            value : 30,
            color : "#FFEA88"

        }
    ];

when I do VAR_DUMP i GET THE FOLLOWING :

array(2) {[0]=>array(2) {["value"]=> string(2) "21"["color"]=>string    
(8) "#878BB6"}[1]=>array(2){["value"]=>string(2)"99"["color"]=>string       
(8)"#878BB6"}}

Just look at your code, Spagetti of HTML , Javascript & PHP .

You should not mix them that way, intead you should make a request using AJAX for example:

  • Let the server side ( PHP ) query your database.
  • Parse the response in your client side( javascript ).

Here is an example:

PHP

<?php
include "config.php";

if (mysqli_connect_errno($con)){
    echo "Failed to connect to DataBase: " . mysqli_connect_error();
}
else
{
    $result = mysqli_query($con, "SELECT Delaytype, COUNT(1) as cnt 
                                  FROM delays GROUP BY Delaytype;");
    $pieData = array();

    while($row = mysqli_fetch_array($result)){   
       $pieData[] = array('value' =>$row['cnt'], 'color' =>'#878BB6 ');
    }
    mysqli_close($con);     
}
 echo json_encode($pieData); 

?>

Javscript

window.onload = function() {
    var hr = new XMLHttpRequest();
    hr.open("GET", "get_pie_data.php", true);
    hr.setRequestHeader("Content-type", "application/json");
    hr.onreadystatechange = function() {
        if(hr.readyState == 4 && hr.status == 200) {
            var pieData = JSON.parse(hr.responseText);
            // pie chart options
            var pieOptions = {
                 segmentShowStroke : false,
                 animateScale : true
            };
            // get pie chart canvas
            var countries= document.getElementById("buy").getContext("2d");
            // draw pie chart
            new Chart(countries).Pie(pieData, pieOptions);

        }
    }
    hr.send(null);
}

If your comfortable with jQuery then look into ajax, it's a little easier to work with.

Hello got chart working final code below. It seems it was not a JSON issue after all. JSON was fine but the quotes around my numbers in the chart data broke the chart. I added the (int) as follows.

Delay TypeDelay Hours"; $pieData = array(); while($row = mysqli_fetch_array($result)) { $pieData[] = array('value' =>(int)$row['cnt'], 'color' =>'#878BB6 '); } ?>
 <script> var pieData = <?php echo json_encode($pieData) ?>;// // pie chart options var pieOptions = { segmentShowStroke : false, animateScale : true }; // get pie chart canvas var countries= document.getElementById("buy").getContext("2d"); // draw pie chart new Chart(countries).Pie(pieData, pieOptions); </script> </body> </html> <?php mysqli_close($con); } ?> 

I did also remove quotes (spaces) from echo of json encode. I did this before I added (int). It did not fix the chart. However I have not tested if the would have broken the chart with the (int) in place.

I still have a problem of trying to get different colors in the chart.

Thanks for input. The question was a little off the real problem. Apologies for that. I didnt know this when posting

Sorry just saw someone wrote this when posting my awnser - thankyou.

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