JSON Array Pie Chart with PHP

  • (2 Pages)
  • +
  • 1
  • 2

16 Replies - 652 Views - Last Post: 12 February 2018 - 03:16 AM Rate Topic: -----

#1 Yhym   User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 48
  • Joined: 08-December 13

JSON Array Pie Chart with PHP

Posted 03 February 2018 - 01:36 PM

I'm trying to display the data I'm receiving from an API in a pie chart but all the examples I can find only show how to do it by manually inputting data so I decided to try here. This is what I've now (Omitted the styling):
<?php
 $allocation = array(
 array('Company Name', 'Allocation'),
 array($name, $sum1), 
);

 $encoded_data = json_encode($allocation);
?>
        <script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
google.setonloadCallback(drawChart);
function drawChart() 
{
 var data = google.visualization.arrayToDataTable(
 <?php  echo $encoded_data; ?>
 );
 var options = {
  title: "Portfolio Allocation"
 };
 var chart = new google.visualization.PieChart(document.getElementById("allocation"));
 chart.draw(data, options);
}
</script>

This is what the var_dump($allocation) gives me: array(2) { [0]=> array(2) { [0]=> string(12) "Company Name" [1]=> string(10) "Allocation" } [1]=> array(2) { [0]=> array(8) { [0]=> string(12) "Facebook Inc" [1]=> string(16) "Alphabet Class A" [2]=> string(9) "Apple Inc" [3]=> string(18) "Ford Motor Company" [4]=> string(17) "Adv Micro Devices" [5]=> string(14) "Morgan Stanley" [6]=> string(20) "Berkshire Hath Hld B" [7]=> string(20) "JP Morgan Chase & Co" } [1]=> float(1142.8) } }

Which means that I'm retrieving the correct names but for some reason only getting the number for the last name. I also get an error that says "Pie chart should have a first column of type string". To explain a bit more, $name is simply an array that's used to store the names of all the companies that are being retrieved with the API and $sum1 is calculated like this (It's a row inside of a table):

$firstno1  = floatval($vol[$x]);
$secondno1 = floatval($lastprice[$x]);
$sum1 = array();
$sum1 = $firstno1 * $secondno1;
print ($sum1);

Is it the way my arrays are structured or something that doesn't allow me to properly retrieve the data I need or what am I missing? Thanks!

Is This A Good Question/Topic? 0
  • +

Replies To: JSON Array Pie Chart with PHP

#2 CTphpnwb   User is online

  • D.I.C Lover
  • member icon

Reputation: 3800
  • View blog
  • Posts: 13,785
  • Joined: 08-August 08

Re: JSON Array Pie Chart with PHP

Posted 03 February 2018 - 08:57 PM

Just a guess, but it seems likely that $encoded_data needs to be json.
Was This Post Helpful? 0
  • +
  • -

#3 CTphpnwb   User is online

  • D.I.C Lover
  • member icon

Reputation: 3800
  • View blog
  • Posts: 13,785
  • Joined: 08-August 08

Re: JSON Array Pie Chart with PHP

Posted 04 February 2018 - 06:29 AM

Oops! I should have been more specific. You have it as a json encoded array, but it probably needs to be a json encoded object.
Was This Post Helpful? 1
  • +
  • -

#4 Yhym   User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 48
  • Joined: 08-December 13

Re: JSON Array Pie Chart with PHP

Posted 04 February 2018 - 06:31 AM

View PostCTphpnwb, on 04 February 2018 - 06:29 AM, said:

Oops! I should have been more specific. You have it as a json encoded array, but it probably needs to be a json encoded object.

Thank you. Would you mind giving me an example of that or some sort of tutorial that I could use? Sorry but I've never done that before, I always just used 'encoded' on its own.
Was This Post Helpful? 0
  • +
  • -

#5 CTphpnwb   User is online

  • D.I.C Lover
  • member icon

Reputation: 3800
  • View blog
  • Posts: 13,785
  • Joined: 08-August 08

Re: JSON Array Pie Chart with PHP

Posted 04 February 2018 - 07:12 AM

<?php
$name = "Apple";
$sum1 = "billions";

$allocation = array(
    array('Company Name', 'Allocation'),
    array($name, $sum1),
);
$test_object = (Object)($allocation);

$json_array = json_encode($allocation);
$json_object = json_encode($test_object);

print_r($json_array);
echo "<br>";
print_r($json_object);



Output:
[["Company Name","Allocation"],["Apple","billions"]]
{"0":["Company Name","Allocation"],"1":["Apple","billions"]}

Was This Post Helpful? 1
  • +
  • -

#6 Yhym   User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 48
  • Joined: 08-December 13

Re: JSON Array Pie Chart with PHP

Posted 04 February 2018 - 09:46 AM

Thanks for your help. Now, I'm not sure why but I'm essentially getting the same result when I do it your way. Meaning I'm able to retrieve all the names but only the correct value for the last name. I've realised something while testing it out and it's the fact that the var_dump($sum1) retrieves the correct values but only when it's placed inside of the table of where it's calculating the results from. That's the result btw: float(6279.24) float(124231.2) float(1605) float(1071) float(124.5) float(554.8) float(2091.2) float(1142.8) (These are the numbers that I want to have on the chart.) Now the question is how do I link these numbers with the names I'm retrieving from the array $name to get them to display onto this chart:

<div id="data">
    	<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
google.setonloadCallback(drawChart);
function drawChart() 
{
 var data = google.visualization.arrayToDataTable(
 // <?php  echo $json_object; ?>
 );
 var options = {
  title: "Portfolio Allocation"
 };
 var chart = new google.visualization.PieChart(document.getElementById("allocation"));
 chart.draw(data, options);
}
</script>


I'm sorry if this is something simple to do but I don't quite get it... I've never done something like this before and so that's why I'm here, to hopefully get some guidance on this. I hope this helps to explain it a little bit more as to what I'm trying to get out of this.
Thanks again!
Was This Post Helpful? 0
  • +
  • -

#7 CTphpnwb   User is online

  • D.I.C Lover
  • member icon

Reputation: 3800
  • View blog
  • Posts: 13,785
  • Joined: 08-August 08

Re: JSON Array Pie Chart with PHP

Posted 04 February 2018 - 10:05 AM

Simply sending a json object isn't enough. It needs to be the correct object. Looking here, it appears that it needs to be a json encoded array of objects and arrays. Their example:

// Version 1: arrayToDataTable method
var data2 = google.visualization.arrayToDataTable([
  [{label: 'Country', type: 'string'},
   {label: 'Population', type: 'number'},
   {label: 'Area', type: 'number'},
   {type: 'string', role: 'annotation'}],
  ['CN', 1324, 9640821, 'Annotated'],
  ['IN', 1133, 3287263, 'Annotated'],
  ['US', 304, 9629091, 'Annotated'],
  ['ID', 232, 1904569, 'Annotated'],
  ['BR', 187, 8514877, 'Annotated']
]);


Was This Post Helpful? 1
  • +
  • -

#8 Yhym   User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 48
  • Joined: 08-December 13

Re: JSON Array Pie Chart with PHP

Posted 04 February 2018 - 11:02 AM

Thank you. I'll look into that and come back if I still can't sort it out.
Was This Post Helpful? 0
  • +
  • -

#9 Yhym   User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 48
  • Joined: 08-December 13

Re: JSON Array Pie Chart with PHP

Posted 11 February 2018 - 03:00 AM

Ok, so I tried to do this in a couple different ways but I just can't get it to work for some reason. I'm just getting a blank space on a site at the moment. 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. All the examples I've seen are using SQL whereas I'm not. I would just like to have a simple pie chart, based on the arrays below. 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>

Was This Post Helpful? 0
  • +
  • -

#10 CTphpnwb   User is online

  • D.I.C Lover
  • member icon

Reputation: 3800
  • View blog
  • Posts: 13,785
  • Joined: 08-August 08

Re: JSON Array Pie Chart with PHP

Posted 11 February 2018 - 07:06 AM

This is not javascript:
        var data = google.visualization.arrayToDataTable($name, $sumOf);

PHP is done by the time Javascript on the browser starts. There are now $name and $sumOf variables any longer.
Was This Post Helpful? 0
  • +
  • -

#11 Yhym   User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 48
  • Joined: 08-December 13

Re: JSON Array Pie Chart with PHP

Posted 11 February 2018 - 07:41 AM

View PostCTphpnwb, on 11 February 2018 - 07:06 AM, said:

This is not javascript:
        var data = google.visualization.arrayToDataTable($name, $sumOf);

PHP is done by the time Javascript on the browser starts. There are now $name and $sumOf variables any longer.

Ok, I see, thanks. How do I now turn these PHP arrays into something that JS will understand then?
Was This Post Helpful? 0
  • +
  • -

#12 CTphpnwb   User is online

  • D.I.C Lover
  • member icon

Reputation: 3800
  • View blog
  • Posts: 13,785
  • Joined: 08-August 08

Re: JSON Array Pie Chart with PHP

Posted 11 February 2018 - 07:54 AM

You could json_encode them and send them to the browser, either as part of the javascript or using ajax.
Was This Post Helpful? 1
  • +
  • -

#13 Yhym   User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 48
  • Joined: 08-December 13

Re: JSON Array Pie Chart with PHP

Posted 11 February 2018 - 09:07 AM

View PostCTphpnwb, on 11 February 2018 - 07:54 AM, said:

You could json_encode them and send them to the browser, either as part of the javascript or using ajax.

I guess that's not the correct way to do this given that I received an error "Pie chart should have a first column of type string" but this is what I've now:
<?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>


So, what am I doing wrong?
Thanks for your help!

This post has been edited by Yhym: 11 February 2018 - 09:08 AM

Was This Post Helpful? 0
  • +
  • -

#14 CTphpnwb   User is online

  • D.I.C Lover
  • member icon

Reputation: 3800
  • View blog
  • Posts: 13,785
  • Joined: 08-August 08

Re: JSON Array Pie Chart with PHP

Posted 11 February 2018 - 11:05 AM

What is your browser seeing as the source code? Is this part:
        var data = google.visualization.arrayToDataTable([
  ['Name', 'Allocation'],
  [ar, ar1]
]);


the same format as post 7?
Was This Post Helpful? 0
  • +
  • -

#15 Yhym   User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 48
  • Joined: 08-December 13

Re: JSON Array Pie Chart with PHP

Posted 11 February 2018 - 12:48 PM

I think this is what it's seeing:

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
(
[0] => 5811.63
[1] => 116135.97
[2] => 1564.1
[3] => 1053
[4] => 113.1
[5] => 521.4
[6] => 1960.2
[7] => 1100.4
)
Was This Post Helpful? 0
  • +
  • -

  • (2 Pages)
  • +
  • 1
  • 2