Frenzyy
Frenzyy

Reputation: 41

Google Charts Dynamic Arrays PHP Without SQL

I'm asking this question because all the answers I could find for similar problems were using MySQL whereas I'm not, just a JSON API to get the data, which I then put into arrays that I want to display as a Google graph. All I know is that I have to somehow format the arrays properly in order to get them to display but I have no idea how to do it in my case. I would just like to have a simple pie chart, based on the arrays below. So far I'm getting a blank space on the site. I tried something with Json_encode before but it didn't work so I decided to leave it as it is and come here instead. Here are the arrays after I do print_r: Array 'name'-

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 )

Array '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 )

Code:

<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>

How arrays are made:

$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);
?>

Upvotes: 0

Views: 243

Answers (2)

Frenzyy
Frenzyy

Reputation: 41

array_combine was needed to join the two arrays together and then inside of 'function drawChart' a simple foreach loop was required, like this:

<?php
foreach ($array as $name => $allocation):
    echo "['$name', $allocation]";
    echo ($allocation != end($array)) ? ',' : '';
endforeach;
?>

Upvotes: 0

saurabh yadav
saurabh yadav

Reputation: 153

Here is the working Example of your code you were very close though. Actually, you have to pass only one single parameter as a multidimensional array to arrayToDataTable(); you have to json_encode and JSON_parse your array as well check https://developers.google.com/chart/interactive/docs/gallery/piechart

No worries its working copy and paste it and you are good to go.

 <?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>

Upvotes: 2

Related Questions