javascript - Google Charts 动态数组 PHP 不带 SQL

标签 javascript php arrays json google-visualization

我问这个问题是因为我能找到的类似问题的所有答案都在使用 MySQL,而我不是,只是使用 JSON API 来获取数据,然后将其放入我想要显示为的数组中谷歌图表。我所知道的是,我必须以某种方式正确格式化数组才能让它们显示,但我不知道在我的情况下该怎么做。我只想根据下面的数组制作一个简单的饼图。到目前为止,我在网站上发现了一个空白区域。我之前尝试过使用 Json_encode 进行一些操作,但它不起作用,所以我决定保持原样,来到这里。这是我执行 print_r 后的数组: 数组“名称”-

Array ( [0] => Facebook Inc [1] => Alphabet Class A [2] => Apple Inc [3] => Ford Motor Company [4] => Adv Micro Devices [5] => Morgan Stanley [6] => Berkshire Hath Hld B [7] => JP Morgan Chase & Co )

数组“sumOf”-

Array ( [0] => 5811.63 [1] => 116135.97 [2] => 1564.1 [3] => 1053 [4] => 113.1 [5] => 521.4 [6] => 1960.2 [7] => 1100.4 )

代码:

<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
    <script type="text/javascript">
      google.charts.load('current', {'packages':['corechart']});
      google.charts.setOnLoadCallback(drawChart);

      function drawChart() {

        var data = google.visualization.arrayToDataTable($name, $sumOf);

        var options = {
          title: 'Portfolio Allocation'
        };

        var chart = new google.visualization.PieChart(document.getElementById('piechart'));

        chart.draw(data, options);
      }
    </script>

<body>
<div id="piechart" style="width: 900px; height: 500px;"></div>
</body>

数组是如何制作的:

$name = [];
$lastprice = [];
$y = 0;
$z = '';
$key = "";

// Retreiving information from database
$memberid = $_SESSION['memberID'];
$sql = "SELECT * FROM portfolio WHERE memberID = $memberid";
$result = mysqli_query($conn, $sql);

// Check if databse is empty
if (mysqli_num_rows($result) > 0) 
{
while($row = mysqli_fetch_assoc($result)) 
{
$sym[$y] = $row["stocks_symbol"];
$pri[$y] = $row["price"];
$vol[$y] = $row["quantity"];
$id[$y] = $row["memberid"];
$y += 1;
}
}
// If database empty
else 
{
echo "Portfolio Empty";
die();
}
mysqli_close($conn);

// Adding all stock names in one variable to enable API call
for($a=0;$a<$y;$a++)
{
$z = $z.$sym[$a].',';
}
$z = rtrim($z,",");


// API call
$contents = file_get_contents("http://marketdata.websol.barchart.com/getQuote.json?key=$key&symbols=$z&mode=R");
$contents = json_decode($contents, true);
// Check successfull API call
if($contents["status"]["code"] == 200) 
{
foreach($contents['results'] as $result) 
{
array_push($name,$result['name']);
array_push($lastprice,$result['lastPrice']);
}
    }        
// If API call unsuccessful
else 
{ 
echo "Error retreiving data. Please try again later.";
die();
}
?>

<!-- Generating Output in tabular format -->
<table id= test class='table table-responsive'>
<tr class='head warning'>
<th>Name</th>
<th>Last Price</th>
<th>Price Bought</th>
<th>Quantity</th>
<th>Change Per Stock</th>
<th>Profit/Loss</th>
<th>Market Value</th>
<th>Amount Invested</th>
</tr>
<?php
$profitOrLossSum = 0;
    $dividendRateSum = 0;
$startEqSum = 0;
$sumOf = array();

for($x=0;$x<$y;$x++) 

{?>
<tr>
<td class="input"><?php echo $name[$x]; ?></td>
<td class="input"><?php echo $lastprice[$x]; ?></td>
<td class="input"><?php echo $pri[$x]; ?></td>
<td class="input"><?php echo $vol[$x]; ?></td>
<td class="input"><?php 
if($pri[$x] > $lastprice[$x]) 
{
echo $lastprice[$x]-$pri[$x];
}
else if($pri[$x] < $lastprice[$x]) 
{
echo $lastprice[$x]-$pri[$x];
}
else
echo '0';
?></td>
<td class="input"><?php 
$profitOrLoss = ($lastprice[$x]-$pri[$x]) * $vol[$x];
                $profitOrLossSum += $profitOrLoss;
                 echo $profitOrLoss;
?></td>
     <td><?php
     $firstno1  = floatval($vol[$x]);
$secondno1 = floatval($lastprice[$x]);
$sumOf[] = $firstno1 * $secondno1;
$sum1 = $firstno1 * $secondno1;
print ($sum1);
?></td>
<td class="input">
           <?php 
                $starteq = $pri[$x] * $vol[$x];
               $startEqSum += $starteq;
                echo $starteq;
            ?> 
            </td>
</tr>
<?php 
    }
    $arr = array('profitOrLossSum' => $profitOrLossSum, 'dividendRateSum' => $dividendRateSum);
    $arr1 = array('startEqSum' => $startEqSum); 
    print_r ($name);
    print_r ($sumOf);
    echo json_encode($name);
    echo json_encode($sumOf);
?>

最佳答案

这是您的代码的工作示例,但您非常接近。实际上,您只需将一个参数作为多维数组传递给 arrayToDataTable();您还必须对数组进行 json_encode 和 JSON_parse 检查https://developers.google.com/chart/interactive/docs/gallery/piechart

不用担心它的工作副本并粘贴它,你就可以开始了。

 <?php
      $name = ['Facebook Inc', 'Alphabet Class A', 'Apple Inc', 'Ford Motor Company', 'Adv Micro Devices', 'Morgan Stanley', 'Berkshire Hath Hld B', 'P Morgan Chase & Co'];
      $sumOf = [5811.63, 116135.97, 1564.1, 1053, 113.1, 521.4, 1960.2, 1100.4];
?>


<html>
    <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
    <script type="text/javascript">
        google.charts.load('current', {'packages': ['corechart']});
        google.charts.setOnLoadCallback(drawChart);
        var name = <?= json_encode($name) ?>;
        var sumOf = <?= json_encode($sumOf) ?>;
        var array = name.split(",");
        newArr = [['Name', 'Amount']];
        array.forEach(function (v, i) {
            newArr.push([v, sumOf[i]]);
        });
        function drawChart() {

            var data = google.visualization.arrayToDataTable(newArr);


            var options = {
                title: 'Portfolio Allocation'
            };

            var chart = new google.visualization.PieChart(document.getElementById('piechart'));

            chart.draw(data, options);
        }
    </script>

    <body>
        <div id="piechart" style="width: 900px; height: 500px;"></div>
    </body>
</html>

关于javascript - Google Charts 动态数组 PHP 不带 SQL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48726372/

相关文章:

javascript - 页面重新加载返回到index.php

php - 将静态站点生成器与 php 集成

java - 给定 "sub-grid"和 "cell-in-the-sub-grid"索引,如何获取数独二维数组索引?

c++ - 得到奇怪的结果作为数组的最后一个元素

c - 降序不能正常工作c编程

javascript - 如何设置 SVG USE 元素的样式/操作内容

php - 如何使用 DateTime 在 PHP 中获取后天?

javascript - React JS - 无法在尚未安装的组件上调用 setState

javascript - 是否可以在 *ngFor 中增加组件属性值?

javascript - 根据变量中是否存在数字绘制不同颜色的圆圈