Frenzyy Posted February 11, 2018 Share Posted February 11, 2018 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 ) <?php echo json_encode($name); echo json_encode($sumOf); ?> <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 ar = <?php echo json_encode($name) ?>; var ar1 = <?php echo json_encode($sumOf) ?>; function drawChart() { var data = google.visualization.arrayToDataTable([ ['Name', 'Allocation'], [ar, ar1] ]); var options = { title: 'Portfolio Allocation' }; var chart = new google.visualization.PieChart(document.getElementById('piechart')); chart.draw(data, options); } </script> 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. Therefore, these graphs would have to be appropriately adjusted whenever input to arrays would be updated. I hope you understand what I mean and would really appreciate if someone could help me out with this. Quote Link to comment Share on other sites More sharing options...
Barand Posted February 11, 2018 Share Posted February 11, 2018 Does array_combine give the array structure you want? echo json_encode( array_combine($name, $sumOf) ); Quote Link to comment Share on other sites More sharing options...
requinix Posted February 11, 2018 Share Posted February 11, 2018 Using that example data you've shown, what is the data structure you're trying to create? And it would help to know the code you used to create those two arrays too. Quote Link to comment Share on other sites More sharing options...
Frenzyy Posted February 11, 2018 Author Share Posted February 11, 2018 Does array_combine give the array structure you want? echo json_encode( array_combine($name, $sumOf) ); When I do that, I just get an empty space on a site. Using that example data you've shown, what is the data structure you're trying to create? And it would help to know the code you used to create those two arrays too. Ok so essentially, my arrays have to match the structure which Google Charts require. Something like this if I'm not mistaken: https://developers.google.com/chart/interactive/docs/reference So hopefully this gives you an idea as to how my structure currently differs to the one which Google wants. As for how I get the arrays: 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 final values for each & 'name' is the array that holds all the added names). And then all I want is to just display a simple pie chart using 'name' & 'sumOf'. it doesn't necessarily have to be done this way, if there are other ways of doing so then let me know too, please, I don't mind. here's the code for the whole thing (Deleted some which didn't apply): $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); ?> <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 ar = <?php json_encode(array_combine($name, $sumOf)); ?>; // var ar1 = <?php echo json_encode($sumOf) ?>; function drawChart() { var data = google.visualization.arrayToDataTable([ ['Name', 'Allocation'], ['ar'] ]); var options = { title: 'Portfolio Allocation' }; var chart = new google.visualization.PieChart(document.getElementById('piechart')); chart.draw(data, options); } </script> </table> if you need any more explanation or other parts of code then let me know. Thanks for your help! Quote Link to comment Share on other sites More sharing options...
Barand Posted February 11, 2018 Share Posted February 11, 2018 So you are asking us to read the documentation for you to find out what structure is required? I have a different approach in mind - guess what it might be. Quote Link to comment Share on other sites More sharing options...
Frenzyy Posted February 11, 2018 Author Share Posted February 11, 2018 (edited) No, not at all... I don't even want an exact answer if that's what you are thinking. A tutorial or a guide of some sort will be enough... I'm just lost because all solutions I can see are done using SQL and as you can see I'm not using SQL to obtain these arrays. I've tried all kinds of different loops and approaches and just couldn't get it to work. Either blank space or error that tells me that the first column has to be a string or something. You asked me what structure is needed so I provided you with a link to the site from which I got the code for the Pie Chart, given that it was the one which I've seen most widely used. If I'm not mistaken, this is what you are looking for, right? https://developers.google.com/chart/interactive/docs/reference#dataparam {"cols": [{"id":"","label":"Topping","pattern":"","type":"string"},{"id":"","label":"Slices","pattern":"","type":"number"}],"rows": [{"c":[{"v":"Mushrooms","f":null},{"v":3,"f":null}]},{"c":[{"v":"Onions","f":null},{"v":1,"f":null}]},{"c":[{"v":"Olives","f":null},{"v":1,"f":null}]},{"c":[{"v":"Zucchini","f":null},{"v":1,"f":null}]},{"c":[{"v":"Pepperoni","f":null},{"v":2,"f":null}]}]} If there are other approaches then like I said, let me know, I don't mind doing this a different way. For example, here's (I think, again, I might be wrong) a solution to my problem but done for SQL. The question is, how do I change that solution to make it work with just JSON? $table = array( 'cols' => array( array('label' => 'priority', 'type => 'string'), array('label' => 'num_count', 'type => 'number') ), 'rows' => array() ); while ($row = mysql_fetch_assoc($result)) { $table['rows'][] = array( 'c' => array( array('v' => $row['priority']), array('v' => $row['num_count']) ) ) } echo json_encode($table, JSON_NUMERIC_CHECK); // edit The problem for me isn't actually displaying the pie chart because if I do it like this: <html> <head> <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', 'Amount'], ['Company', 121], ['Company2', 22], ['Company3', 22] ]); var options = { title: 'Allocation' }; var chart = new google.visualization.PieChart(document.getElementById('piechart')); chart.draw(data, options); } </script> </head> <body> <div id="piechart" style="width: 900px; height: 500px;"></div> </body> </html> Then it works, no problem. All I'd like to achieve is to simply have the values from array 'name' go into the column 'Name' and values from array 'sumOf' into the column 'Amount'. I hope this helps a little bit. Thank you. Edited February 11, 2018 by Frenzyy Quote Link to comment Share on other sites More sharing options...
Solution Frenzyy Posted February 12, 2018 Author Solution Share Posted February 12, 2018 array_combine was needed to join the two arrays together and then inside of 'function drawChart' a simple foreach loop was required, like this: <?phpforeach ($array as $name => $allocation):echo "['$name', $allocation]";echo ($allocation != end($array)) ? ',' : '';endforeach;?> Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.