วันจันทร์ที่ 1 สิงหาคม พ.ศ. 2565

PHP Create JSON File Write/Read by Ging009

 การสร้าง JSON จาก PHP

<?php
$connection = mysqli_connect("8.8.8.8","google","google","mydatabase") or die("Error " . mysqli_error($connection));
//connect database----1------
$sql = "SELECT * from mytb";
$result = mysqli_query($connection, $sql) or die("Error in Selecting " . mysqli_error($connection));
//connect database----2------
$sql1 = "SELECT * FROM mytb1
$result1 = mysqli_query($connection, $sql1) or die("Error in Selecting " . mysqli_error($connection));
//create an array
$day01 = array();
while($row1 =mysqli_fetch_assoc($result))
{
$day01[] = $row1;
}
echo json_encode($day01); //แสดงข้อมูลที่จะ Write Json File
$day02 = array();
while($row2 =mysqli_fetch_assoc($result1))
{
$day02[] = $row2;
}
echo json_encode($day02); //แสดงข้อมูลที่จะ Write Json File

//close the db connection
mysqli_close($connection);
 //write to json file
    $fp1 = fopen('myjson01.json', 'w');
        fwrite($fp1, json_encode($day03));
    fclose($fp1);
    $fp2 = fopen('myjson02.json', 'w');
        fwrite($fp2, json_encode($day02));
    fclose($fp2);
?>

การนำ JSON ไปใช้งานใน PHP

<?php
//ดึง Json ไฟล์มาใช้งาน
$url_total = 'myjson01.json';
$jsontotal = file_get_contents($url_total); //ดึงข้อมูลจาก Content
$data = json_decode( $jsontotal); //json_decode แปลงไฟล์ JSON เป็น Array
    for( $j=0; $j<count($data); $j++ ) {
$mydate1[] = $data[$j]->mydate;  //mydateคือ Field ใน Database
$mytotal[] = $data[$j]->total_rel;  //total_rel คือ Field ใน Database
    }
// กรณีต้องการดึงค่าสุดท้ายไปใช้งานด้วย
$last_date= $mydate[count($data )-1]; //count($data)-1 คือเอาค่า count สุดท้าย $last_total= array_sum($mytotal); //ผลรวมของค่า total_rel

การแสดงผล ก็สามารถ


<body>  
<center><h2> ข้อมูลการระบายน้ำวันที่ <u><?=date('d/m/Y',strtotime($mydates));?>   &nbsp;&nbsp;เวลา : 00:00 - <?php  if($mytimes == '23:59'){echo "24:00";} else {echo $mytimes ;} ?> น. </u></h2>
</center>
<table align = "center" border=1>
<tr align="center">
    <th>Date</th>
    <th>Time</th>
    <th>CMS</th>
</tr>
<?php 
foreach($v as $item) {?>
<tr align="center">
     <td><?php echo $item->mydate; ?></td>
     <td><?php echo $item->mytime; ?></td>
     <td><?php echo $item->sk_cms ;?></td>
 </tr>
<?php  }?>
<tr align="center">
     <td colspan="2"><?php echo "TOTAL"; ?></td>
     <td><?php echo number_format($last_total,0) ;?></td>
 </tr>
</table>
</body>

สำหรับการใช้งานกราฟที่รองรับไฟล์ JSON

CHART.JS

 <script type="text/javascript" src="https://code.jquery.com/jquery-2.1.3.js"></script> 
 <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.1.6/Chart.bundle.min.js"></script> 

<div style="width:90%; height:90%; padding-left:50" align="center"><canvas id="myChart" width="700" height="300"></canvas></div>

<script type="text/javascript">
$(window).load(function(){
var canvas = document.getElementById("myChart");
var ctx = canvas.getContext("2d");
var horizonalLinePlugin = {
  afterDraw: function(chartInstance) {
    var yScale = chartInstance.scales["y-axis-0"];
    var canvas = chartInstance.chart;
    var ctx = canvas.ctx;
    var index;
    var line;
    var style;
    if (chartInstance.options.horizontalLine) {
      for (index = 0; index < chartInstance.options.horizontalLine.length; index++) {
        line = chartInstance.options.horizontalLine[index];
        if (!line.style) {
          style = "rgba(169,169,169, .6)";
        } else {
          style = line.style;
        }
        if (line.y) {
          yValue = yScale.getPixelForValue(line.y);
        } else {
          yValue = 0;
        }
        ctx.lineWidth = 3;
        if (yValue) {
          ctx.beginPath();
          ctx.moveTo(0, yValue);
          ctx.lineTo(canvas.width, yValue);
          ctx.strokeStyle = style;
          ctx.stroke();
        }
        if (line.text) {
          ctx.fillStyle = style;
          ctx.fillText(line.text, 0, yValue + ctx.lineWidth);
        }
      }
      return;
    };
  }
};
Chart.pluginService.register(horizonalLinePlugin);
var data = {
labels: <?=json_encode($mytime);?>//กำหนดให้เป็น Json Format ก่อน ["00:00","00:01"]
datasets: [{
label: 'Summary Sirikitdam Water Flow m3/s',
data: <?=json_encode($cms);?>//กำหนดให้เป็น Json Format ก่อน
scaleOverride: false,
scaleSteps: 0,
scaleStartValue: 0,
scaleStepWidth: 1,
pointRadius: 0, 
backgroundColor: [
'rgba(50,205,50,1)'
],
borderColor: [
'rgba(0, 100, 64, 1)'
],
borderWidth: 2
}]
};
var myChart = new Chart(ctx, {
  type: 'line',
  data: data,
  options: {
responsive: true,
scales: {
yAxes: [{
scaleLabel: {
display: true,
labelString: 'FLOW RATE (m3/s)'
},
ticks: {
max: 800,
min: 0,
stepSize: 100
}
}],
/* xAxes: [ {
          type: 'time',
          display: true,
          scaleLabel: {
            display: true,
            labelString: 'Time'
          },
          ticks: {
            major: {
              fontStyle: 'bold',
              fontColor: '#FF0000'
            }
          }
        }] */
xAxes: [{
ticks: {
maxRotation: 90,
minRotation: 80,
maxTicksLimit: 49,
stepSize: 10
}
}] 
},
    "horizontalLine": [{
"y": 800,
      "style": "rgba(255, 0, 0, .5)",
      "text": "              ▼     RELEASE 4 UNIT"
    },{
      "y": 600,
      "style": "rgba(30, 180, 0, .5)",
      "text": "              ▼     RELEASE 3 UNIT"
    }, {
      "style": "rgba(238, 130, 238, .5)",
      "y": 400,
      "text": "              ▼     RELEASE 2 UNIT"
    }, {
      "style": "rgba(0, 0, 0, .4)",
      "y": 200,
      "text": "              ▼     RELEASE 1 UNIT"
    }]
  }
});
    });

      </script> 

ไม่มีความคิดเห็น:

แสดงความคิดเห็น