Retrieving data from Google APIs and populate twice - php

I need your help because I'm stuck on how to get secondary datas from Google API and show them on a graph, let me explain :
I've successfully retrieved "visits" datas from the Google Analytics API and show them on my chart with this code :
$report3 = $ga->getReport(
array('dimensions'=>urlencode('ga:date'),
'metrics'=>urlencode('ga:pageviews,ga:visits'),
'filters'=>urlencode(''),
'sort'=>'ga:date'
)
);
Which give me an array like :
[20110726] => Array
(
[ga:pageviews] => 0
[ga:visits] => 0
)
Then I put these informations on the chart with :
<script type='text/javascript'>
var ga_data = [
<?php
$str = "";
foreach ($report3 as $value)
$str.="{$value["ga:visits"]},";
$str = rtrim($str,",");
echo $str;
?>
];
</script>
And finally :
// Create the data table.
var data = new google.visualization.DataTable();
data.addColumn('string', 'Month');
data.addColumn('number', 'visits');
data.addRows(ga_data.length*1);
for (i=9; i<ga_data.length; i++){
data.setValue(i, 0, 'DATE NEEDED');
data.setValue(i, 1, ga_data[i]);
}
The only problem is that I need to show the DATE : ([20110726] => Array
(
[ga:pageviews] => 0
[ga:visits] => 0
)) on the chart like I do with visits
Any help will be very very appreciated ! Thanks !!!

Looks like the data coming back has the date as the index of the array (a.k.a. 'Dimension'). Just update your loop to get that like so.
foreach(ga_data as $date=>$values){
data.setValue(i, 0, $date);
data.setValue(i, 1, $values['ga:visits']);
}
You might need to split the date into its parts if the DataVisualization API can't handle that type like so:
$str = '20110726';
$year = substr($str,0,4);
$month = substr($str,4,2);
$day = substr($str,6,2);
Then format to your liking with the PHP date() function.

Related

PhP Convert a multidimensional array column by column?

I'm trying to build a google chart column chart where each column represents a property (house), and the income, per year of that property. The year would be represented on the x-axis, and the y-axis represents the income amount.
End result in JS would need to look like this:
var columnChartData = google.visualization.arrayToDataTable([
['Year', 'Property 1', 'Property 2'],
['2022', 300, 4000],
['2023', 6000, 8000]
]);
I'm currently struggling with converting my PHP array below, to the required google format. How can I build an array column by column?
array([Property 1] => Array ( [2021] => 353.93 [2022] => 12628.65 [2023] => 12841.57 )
[Property 2] => Array ( [2022] => 370.78 [2023] => 12841.57 ))
required JS/GoogleChart:
['Year', 'Property 1', 'Property 2'],
['2022', 300, 4000],
['2023', 6000, 8000]
Here is one approach. This heavily relies on the assumption that for each property, a record for the Year is included. For example, we are assuming that the nth element of Property1 has the same year as the nth element of Property2.
Note, if OP controls the source with SQL or some other data source, it would be much easier to use PIVOT which is available in many RDBMS (but notably not mySQL). Likewise, using a charting framework like plotly might be helpful as well - I like the examples from this website which shows us using two separate data sources on the same plot area. We could imagine applying this by having a dataset for Property1 and a separate one for Property2.
https://plotly.com/javascript/line-charts/
<?php
$data = ["Property1" => [2022=>300, 2023=>6000], "Property2" => [2022=>4000, 2023=>8000]];
// Reshape so that each row consists of [Year, Property1, Property2]
$formattedArray = array_map(function ($year, $prop1, $prop2) {
return [$year, $prop1, $prop2];
},
array_keys($data["Property1"]),
array_values($data["Property1"]),
array_values($data["Property2"]));
// Add a header
$res = array_merge([["Year", "Property1", "Property2"]], $formattedArray);
// Method 2
$keys = array_keys($data);
$res2 = [array_merge(["Year"], $keys)];
// assume each property has the same years
$years = array_keys($data[$keys[0]]);
for ($i = 0; $i<count($years); $i++) {
$thisRow = [$years[$i]];
foreach($data as $prop) {
array_push($thisRow, array_values($prop)[$i]);
}
array_push($res2, $thisRow);
}
print_r($res2);
?>
<html>
<head> <!--Load the AJAX API-->
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
let thisData = <?php echo json_encode($res);?>;
// Load the Visualization API and the corechart package.
google.charts.load('current', {'packages':['corechart']});
// Set a callback to run when the Google Visualization API is loaded.
google.charts.setOnLoadCallback(drawChart);
// Callback that creates and populates a data table,
// instantiates the scatter chart, passes in the data and
// draws it.
function drawChart() {
// Create the data table.
<?php echo "var chartData = google.visualization.arrayToDataTable(" . json_encode($res2) . ");"?>
// Set chart options
var options = {'title':'Different Properties By Year',
'width':600,
'height':400};
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.ScatterChart(document.getElementById('chart_div'));
chart.draw(chartData, options);
}
</script>
</head>
<body>
<!--Div that will hold the pie chart-->
<div id="chart_div"></div>
</body>
</html>

showing array content wordpress

I am new in wordpress and I confuse how to solve this.
$redeem = array(
date('Ymd'),
$_POST['value']
);
if ($point && is_array($point)) {
$n = sizeof($point);
$point[$n] = $redeem;
}
update_user_meta(get_current_user_id(), 'value', $point);
} else {
update_user_meta(get_current_user_id(), 'value', $redeem );
}
This code work properly, it makes the data in my database become array. The problem is, how can I show the data from my database into my work page ?
a:3:{i:0;s:8:"20160421";i:1;s:3:"222";
This is the result of value in my database. I just want to show the value of "222".
Thanks
In WordPress, when you insert/update array data into user_meta or post_meta table, it will automatically saves data in serialized form, so you have to unserialize those data while fetching.
Below you can find simple conversation for array to serialized data and serialized data to array. You have to pass serialized data into unserialize function to fetch 222 value.
$arr = array("name"=>"milap","language"=>"php","cms"=>"WordPress");
$sd = serialize($arr);
$res = unserialize($sd);
echo "<pre>";print_r($res);
The output of above code is,
Array
(
[name] => milap
[language] => php
[cms] => WordPress
)

Use MySQL data as the chart data for the cakephp highchart plugin

I would like to use the highchart plugin in cakephp. I installed it and I can run all the demos that come with the plugin.
I would like to use it in my own controller and took one of the examples as an implementation guide.
If I have the following code in my controller it does NOT work, i.e. highchart does not display any of the input values.
$resultStatistics = $this->Statistic->find("all", $params = array( 'fields' => 'new_students_total','recursive' => -1) );
$chartData1 = array();
$chartData1 = Hash::extract($resultStatistics, '{n}.Statistic.new_students_total');
// $chartData1 = array(0=>5, 1=>5, 2=>4, 3=>4);
$this->print_r2($chartData1);
$chartName = 'Evolution of Actual Number of Students';
$mychart = $this->Highcharts->create($chartName, 'line');
$this->Highcharts->setChartParams($chartName, array(
'renderTo' => 'linewrapper', // div to display chart inside
'chartWidth' => 600,
'chartHeight' => 500,
'chartMarginTop' => 60,
'chartMarginLeft' => 90,
'xAxisCategories' => array('Jan', 'Feb', 'Mar', 'Apr'),
// autostep options
// 'enableAutoStep' => TRUE
)
);
$series1 = $this->Highcharts->addChartSeries();
$series1->addName('ABC')
->addData($chartData1);
$mychart->addSeries($series1);
$this->set(compact('chartName'));
The result from the database query is a simple array with 4 integer values.
But if I uncomment the line 4, “$chartData1 = array(0=>5, 1=>5, 2=>4, 3=>4);”, basically defining the values of the array manually it DOES WORK and a linechart is drawn. I use Cakephp 2.4.3 and PHP 5.6
I can't seem to figure out the difference between the "mysql" version of the array $chartData1 and the "manual defined" version of $chartData1. What am I missing?
After lots of checking I eventually found the problem. The Cake plug in helper expects integer (or reals) in the chartData1 array. So simple adding the following lines:
foreach ($resultStatistics as $result) {
$chartData[] = (int) $result['Statistic']['new_students_total'];
}
at last solved my problem.
Thank anyway for your help

Exclude value if under a certain percentage

I am trying to make a pie chart, using chartjs, to display almost all the data in a database. What it does is count how many times a certain word is used in the database and it uses that count as the value and the word as the name.
In my pie chart I have almost 10 values that are about .01% of the pie chart and i'm trying to remove them.
Anyone have any ideas?
Also google searching this makes it seem like chartjs is not that popular nor supported, would it be more reasonable to use something else?
EDIT:
cakephp MODEL:
function pieChart($conditions = null) {
//Get Data for PieChart
$this->RecordDrug->virtualFields['sum'] ='COUNT(*)';
$records = array();
$records=$this->RecordDrug->find('list',
array(
'conditions' => $conditions,
'fields' => array( 'Drug.drug', 'sum'),
'contain' => array( 'Drug', 'Record' ),
'group' => 'Drug.Drug'
));
return $records;
}
CONTROLLER:
$pieChart = $this->Record->pieChart();
$this->set('output',$pieChart);
VIEW:
var pieChartDataSource = [
<?php
foreach($output as $compound => $sum){
echo "{category: '".$compound."', value: ".$sum."}, ";
}
?>
];
I think what you need is to filter your dataset before calling chartjs to create the chart. Is there any reason not to do that?
$sumofvars=array_sum($output);
$above_percent=0.1;
foreach($output as $compound => $sum){
$percentage_to_eliminate=($sum/$sumofvars)*100;
if ($percentage_to_eliminate>$above_percent)
{
echo "{category: '".$compound."', value: ".$sum."}, ";
}
}
?>
];

Dynamically add data stored in php to nested json

I am trying to dynamicaly generate data in json for jQuery gantt chart. I know PHP but am totally green with JavaScript. I have read dozen of solutions on how dynamicaly add data to json, and tried few dozens of combinations and nothing. Here is the json format:
var data = [{
name: "Sprint 0",
desc: "Analysis",
values: [{
from: "/Date(1320192000000)/",
to: "/Date(1322401600000)/",
label: "Requirement Gathering",
customClass: "ganttRed"
}]
},{
name: " ",
desc: "Scoping",
values: [{
from: "/Date(1322611200000)/",
to: "/Date(1323302400000)/",
label: "Scoping",
customClass: "ganttRed"
}]
}, <!-- Somoe more data-->
}];
now I have all data in php db result. Here it goes:
$rows=$db->fetchAllRows($result);
$rowsNum=count($rows);
And this is how I wanted to create json out of it:
var data='';
<?php foreach ($rows as $row){ ?>
data['name']="<?php echo $row['name'];?>";
data['desc']="<?php echo $row['desc'];?>";
data['values'] = {"from" : "/Date(<?php echo $row['from'];?>)/", "to" : "/Date(<?php echo $row['to'];?>)/", "label" : "<?php echo $row['label'];?>", "customClass" : "ganttOrange"};
}
However this does not work. I have tried without loop and replacing php variables with plain text just to check, but it did not work either. Displays chart without added items. If I add new item by adding it to the list of values, it works. So there is no problem with the Gantt itself or paths. Based on all above I assume the problem is with adding plain data to json. Can anyone please help me to fix it?
First of all you're adding properties to string instead of building object. If you really want to do that this way:
var data = [], row;
<?php foreach ($rows as $row) : ?>
row = {};
row.name ="<?php echo $row['name'];?>";
row.desc ="<?php echo $row['desc'];?>";
row.values = {"from" : "/Date(<?php echo $row['from'];?>)/", "to" : "/Date(<?php echo $row['to'];?>)/", "label" : "<?php echo $row['label'];?>", "customClass" : "ganttOrange"};
data.push(row);
<?php endforeach; ?>
Anyway it is unsafe (and result is normal JS code, not proper JSON object - but as you're assigning it to variable then I suppose it does not have to be in strict JSON format)
Better approach would be to build data structure in PHP and use json_encode function to generate JSON data for JavaScript:
<?php
$data = array();
foreach ($rows as $row) {
$data[] = array(
'name' => $row['name'],
'desc' => $row['desc'],
'values' => array(array(
'from' => '/Date('.$row['from'].'>)/',
'to' => '/Date('.$row['to'].')/',
'label' => $row['label'],
'customClass' => 'ganttOrange',
))
);
}
?>
var data = <?php echo json_encode($data); ?>;
Quick Answer
As stated previously, this problem is easily resolved using the PHP json_encode function.
The trick to understanding how to do this easily is to understand the composite data structure that you are trying to work with.
Overview
What you are dealing with is a general programming concept called a "composite data structure". The trick to understanding this is to realize that the PHP and the JavaScript that you are attempting to manage are just two different representations of the exact same thing.
Once this concept sinks in, it will be easy to relate to what the users Musa and dev-null-dweller have already explained.
The straightforward way to solve this issue is to simply build a composite data structure in PHP and then translate it into JSON (aka JavaScript) using the built-in native methods of PHP's json_encode and json_decode.
Instead of doing all the statements, you should treat each $row as a composite data structure and use the PHP json functions.
The following example should give you a head start, simply compare it to the data you are trying to work with and change accordingly.
Example 001
// This is a PHP composite data structure [ a nested array ]
// represented in PHP. When you run this code you will get the
// output of Result 001
$user_profile = Array(
main => Array(
first_name => "_blank_",
last_name => "_blank_",
sex => "_blank_",
age => "_blank_",
),
guardian => Array(
first_name => "",
last_name => "",
),
children => Array(
0 => Array(
first_name => "Sally",
last_name => "Shaw",
),
1 => Array(
first_name => "Scott",
last_name => "Shaw",
),
),
);
// This is some sample PHP code you can use to modify
// the composite data structure (modify the "_blank_" values)
//
$user_profile["main"]["first_name"] = "Archibald";
$user_profile["main"]["last_name"] = "Shaw";
$user_profile["main"]["age"] = "33";
$user_profile["main"]["sex"] = "male";
// This is some sample PHP code you can use to modify
// the composite data structure (add a new child)
//
$user_profile["children"][2] = Array();
$user_profile["children"][2]["first_name"] = "Carrie";
$user_profile["children"][2]["last_name"] = "Shaw";
// This is the PHP code you can use to transform from PHP to JSON
$result = json_encode( $user_profile );
print_r( $result );
Result 001 (formatted for easy readability)
{
"main":{
"first_name":"Archibald",
"last_name":"Shaw",
"sex":"male",
"age":"33"
},
"guardian":{
"first_name":"",
"last_name":""
},
"children":[
{
"first_name":"Sally",
"last_name":"Shaw"
},
{
"first_name":"Scott",
"last_name":"Shaw"
},
{
"first_name":"Carrie",
"last_name":"Shaw"
}
]
}
Conclusion
Using the example above, you should first do a print_r of the PHP variable you are trying to work with and get an idea of the overall structure. Once you know this, it is an easy step to convert it to JSON using the built-in PHP json_encode function.
References
http://en.wikibooks.org/wiki/PHP_Programming/Data_Structures#The_Basics
http://en.wikipedia.org/wiki/Composite_type
var data=[];
<?php
foreach ($rows as $row)
{
$obj = array(
'name' => $row['name'],
'desc' => $row['desc'],
'values' => array(
array(
"from" => "/Date({$row['from']})/",
"to" => "/Date({$row['to']})/",
"label" => $row['label'],
"customClass" => "ganttOrange",
)
)
);
$objJson = json_encode($obj);
echo "data.push({$objJson});\n";
}
?>
You should create the data structure in php and echo it out with json_encode.
<?php
$data = array();
foreach ($rows as $row){
$item = array();
$item['name']=$row['name'];
$item['desc']=$row['desc'];
$item['values']= array("from" => "/Date{$row['from']})/",
"to" => "/Date({$row['to']})/",
"label" => $row['label'],
"customClass" => "ganttOrange");
$data[] = $item;
}
echo "\nvar data = ".json_encode($data).";\n";

Categories