0

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);
?>
4
  • Had a look at this because it was flagged as a SQL question. It has been a long time since I have dealt with Google charts, but what you have here looks like what I remember - I think you're close. Commented Feb 11, 2018 at 4:16
  • I'm pretty sure that I just have to format these arrays in a specific way so that Google Charts can use them to fill in the graphs but just not sure how to do so in this case. Commented Feb 11, 2018 at 9:36
  • Yep, but I'm afraid it's been too long for me to know exactly what it is. Sorry. Good luck. Commented Feb 11, 2018 at 9:39
  • Sure. I updated the original question & deleted some unnecessary code to save space. Commented Feb 11, 2018 at 21:55

2 Answers 2

2

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>
Sign up to request clarification or add additional context in comments.

5 Comments

any clarification you can ask again
This is working great so thanks for that but the thing with mine is that these arrays are generated dynamically. Meaning that at any point in time, something can be added or taken away from them by the user. Here, the input into arrays is done manually which won't work if the actual inputs change, which they will over time. Therefore, these graphs would have to be appropriately adjusted. I hope you understand what I mean and would really appreciate if you could help me out with that. Thanks again!
@Frenzyy sorry for late reply but this piece of code will work until you will have the same number of items in both the arrays. so if there would be some change in the second array you just have to change the value in the sumOf array.basically, you will have to modify the array in your PHP code I don't know how will you use this code but I will work if you just modify your array in your PHP code and fed it to this code.Lemme know you need some help
See that's the problem because I don't want to have to modify the array inside of php. I want it to be done automatically, same way as it can be done with SQL but here w/o it, given that these values are not stored in a db. Let me try to clarify a bit more how this should work. 1 User adds company X & Y to their portfolio 2 User adds prices at which they bought and how many shares. 3 The site calculates the overall value of each position (sumOf is the array which holds all these value for each & 'name' is the array that holds all the added names) 4. Pie chart is displayed using 'name' & 'sumOf
In that case, you will have to do it with js and keep looking for an input field to change. so, whenever there will a change you will have to modify your array in javascript and ultimately you have to redraw the graph by calling chart.draw(data,option) . you have to use javascript simply
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.