'PHP 배열 값 추출'에 해당되는 글 1건

728x90

https://mdbootstrap.com/docs/b4/jquery/javascript/charts/

 

Bootstrap Charts Guideline - examples & tutorial

Bootstrap charts are graphical representations of data. Charts come in different sizes and shapes: bar, line, pie, radar, polar and more.

mdbootstrap.com

기본적인 예제가 나와 있다.

이 예제를 가지고 DB와 연동하여 처리하는 방법이다.

 

 

<?php
error_reporting(0);
//*
ini_set("display_startup_errors"1);
ini_set("display_errors"1);
error_reporting(E_ALL);
// */
 
require_once 'path.php';// root 폴더를 기준으로 상대적인 경로 자동 구하기
require_once $g['path_root'].'sessionChk.php'// 세션 체크
require_once $g['path_config'].'config.php';
require_once $g['path_config'].'dbconnect.php';
require_once $g['path_class'].'statsClass.php';
$b = new statsClass();
 
$link_url = "Stats.php"// 현재 실행중인 파일명 가져오기
 
$ageData = $b->ageCnt_array();
 
?>
<p class="h4 mb-4">통계</p>
<div class="row">
    <div class="col-md-8 col-xl-8 col-lg-7">
        <div class="col-md-11">
            <canvas id="Trend1Chart"></canvas>
        </div>
        <div class="col-md-11  mb-4">
            
        </div>
        <div class="col-md-11">
            <canvas id="Trend3Chart"></canvas>
        </div>
    </div>
 
    <div class="col-md-4 col-xl-4 col-lg-5">
        <div class="card shadow mb-4">
            <div class="card-header py-3">
                <h6 class="m-0 font-weight-bold text-primary">연령대</h6>
            </div>
            <div class="card-body">
                <div class="chart-pie pt-4">
                    <canvas id="ageChart"></canvas>
                </div>
            </div>
        </div>
 
    </div>
</div>
 
<script>
  var ctxD = document.getElementById("ageChart").getContext('2d');
  var ageKey = <?php echo json_encode(array_keys($ageData));?>;
  var ageData = <?php echo json_encode(array_values($ageData));?>;
  var myLineChart = new Chart(ctxD, {
    type: 'doughnut',
    data: {
      labels: ageKey,
      datasets: [{
        data: ageData,
        backgroundColor: ["#F7464A""#46BFBD""#FDB45C""#949FB1""#4D5360"],
        hoverBackgroundColor: ["#FF5A5E""#5AD3D1""#FFC870""#A8B3C5""#616774"]
      }]
    },
    options: {
      responsive: true
    }
  });
</script>

 

PHP 배열을 Javascript 변수로 사용하는 방법이 핵심이다.

 

PHP에서 생성된 배열을 자바스크립트에서 사용하는 방법

<?php
$arr_php = array("a","b","c","d");
?>

위 값처럼 선언된 배열을 javascript에서 받아서 사용하려면?

var arr_js = <?php echo json_encode($arr_php)?>;

json_encode 해서 받으면 된다.

json_encode 함수를 사용하면 1차원 배열이든 2차원 배열이든 간단하게 자바스크립트 배열로 만들어 준다.

array_keys($array)  : 배열의 키값을 배열로 반환해주는 함수

array_values($array)  : 배열의 값을 배열로 반환해주는 함수
 
아래 statsClass 의 함수 구현한 것을 살펴보면 PHP 배열을 key, value 로 된 형태로 반환하는 것을 알 수 있다.
<?php
class statsClass {
    function ageCnt_array(){
        global $db;
        $sql = "select age, sum(Cnt) from stats group by age";
        $result = mysqli_query($db,$sql);
        $R=array();
        $TCNT = $this->ageTotalCnt();
        while($row = mysqli_fetch_row($result)){
            $row[0= $row[0].'('.$this->Percentage($row[1],$TCNT).'%)';
            $R[$row[0]] = $row[1];
        }
        return $R// 배열로 반환
    }
 
    function ageTotalCnt(){
        global $db;
        $sql = "select sum(Cnt) from stats";
        $result = mysqli_query($db,$sql);
        if($row = mysqli_fetch_row($result)){
            return $row[0];
        }
    }
 
    function Percentage($val,$TCNT){
        $percent = $val / $TCNT * 100;
        return round($percent,1);
    }
 
}
?>

 

 

블로그 이미지

Link2Me

,