Google Analytics Core Reporting API PHP Query - php

This is my first attempt to work with the Core Reporting API. I have successfully made it through the Hello Analytics tutorial and making API requests with no issue. My problem lies with querying the API for using Dimensions, Metrics, and Filters. Below is the code I am working with.. I am able to display how many visitors I have between the first of the month and the current day. Then it displays how many of these came from organic search. I am hoping someone can give me an example on querying the API with a more complex request.. perhaps including Dimensions, Metrics, Filters.. and then displaying then in rows. Any help is much appreciated. Below is my code so far...
//QUERY THE CORE REPORTING API
function getResults($analytics, $profileId, $first_day, $today) {
return $analytics->data_ga->get(
'ga:' . $profileId,
$first_day,
$today,
'ga:visits, ga:organicSearches');
}
//OUTPUT THE RESULTS
function printResults(&$results) {
if (count($results->getRows()) > 0) {
$profileName = $results->getProfileInfo()->getProfileName();
$rows = $results->getRows();
$visits = $rows[0][0];
$organic = $rows[0][1];
print "<h1>$profileName</h1>";
echo '<table border="1" cellpadding="5">';
echo '<tr>';
echo '<td>Visits</td>';
echo '<td>Organic</td>';
echo '</tr>';
echo '<tr>';
echo '<td>'. $visits . '</td>';
echo '<td>'. $organic . '</td>';
echo '</td>';
echo '</table>';
} else {
print '<p>No results found.</p>';
}
}

Here is the code:
$optParams = array(
'dimensions' => 'ga:date,ga:customVarValue1,ga:visitorType,ga:pagePath',
'sort' => '-ga:visits,ga:date',
'filters' => 'ga:visitorType==New',
'max-results' => '100');
$metrics = "ga:visits";
$results = $analytics->data_ga->get(
'ga:' . $profileId,
'2013-03-01',
'2013-03-10',
$metrics,
$optParams);
For displaying the result:
function getRows($results) {
$table = '<h3>Rows Of Data</h3>';
if (count($results->getRows()) > 0) {
$table .= '<table>';
// Print headers.
$table .= '<tr>';
foreach ($results->getColumnHeaders() as $header) {
$table .= '<th>' . $header->name . '</th>';
}
$table .= '</tr>';
// Print table rows.
foreach ($results->getRows() as $row) {
$table .= '<tr>';
foreach ($row as $cell) {
$table .= '<td>'
. htmlspecialchars($cell, ENT_NOQUOTES)
. '</td>';
}
$table .= '</tr>';
}
$table .= '</table>';
} else {
$table .= '<p>No results found.</p>';
}
return $table;
}
You can have better understanding if you try to get this demo working.
Also refer to this code

This is the definition of data_ga->get function in the api source.
public function get($ids, $startDate, $endDate, $metrics, $optParams = array())
{
$params = array('ids' => $ids, 'start-date' => $startDate, 'end-date' => $endDate, 'metrics' => $metrics);
$params = array_merge($params, $optParams);
return $this->call('get', array($params), "Google_Service_Analytics_GaData");
}
complete parameter list is here
all parameters except ids,startdate, enddate and metrics are optional and needs to be sent as associative array as 5th argumant of get function.

Related

Create a bidimensional array in php

I confess that I am a beginner. My goal is to be able to summarize in a two-dimensional table the amount per month (in column) for each class (in line). After doing a lot of research, I arrived at this stage in my project.
My problem is , I get the result with months repeating in columns like here.
Here is my code.
This is my sql code : "SELECT classe, mois, sum_ec FROM journal"
This is my php code :
<?php
$tableau = array();
$tblClasse = array();
$rt = mysqli_query($db, $req_sit);//execute la requete
while ($row = $rt->fetch_assoc()){ //forme le tableau
$tableau[$row['classe']][$row['mois']] = $row['sum_ec'];
if (!in_array($row['classe'],$tblClasse)) {
$tblClasse[] = $row['mois'];
}
}
echo '<table border="1">
<tr>
<th> </th>';
foreach ($tblClasse as $classe) {
echo '<th>' . htmlspecialchars($classe) . '</th>';
}
echo '</tr>';
foreach ($tableau as $mois=>$value) {
echo '<tr>';
$new_line = TRUE;
foreach ($tblClasse as $classe) {
if ($new_line) {
echo '<td>' . $mois . '</td>';
$new_line = FALSE;
}
$display = isset($value[$classe]) ? $value[$classe] : " ";
echo '<td>' . $display . '</td>';
}
echo '</tr>';
}
?>
Can someone tell me what mistake I made?
The problem is in this part of your code:
if (!in_array($row['classe'],$tblClasse)) {
$tblClasse[] = $row['mois'];
}
You are adding months (Fev, Mar) to the array and trying to check if it contains classes (PS, MS etc.) which is impossible, and this condition always returns true, so Feb is added to the $tblClasse array at each iteration. You must either check months or classes and add months or classes to the array respectively. And if you want the array to contain unique values (for example, months), use keys instead of values:
if (!array_key_exists ($row['mois'],$tblClasse)) {
$tblClasse[$row['mois']] = 1;
}
Where 1 can be replaced with any other value.
In the further part of your code use the keys, not values of $tblClasse array to form the table heading.
foreach (array_keys ($tblClasse) as $mois) {
echo '<th>' . htmlspecialchars($mois) . '</th>';
}
Eureka! It worked. I just had to change the line for the values ​​to "array_keys"
foreach (array_keys($tblClasse) as $classe) {
if ($new_line) {
echo '<td>' . $mois . '</td>';
$new_line = FALSE;
}
as well and boom! It's perfect. Thank you very much my dear. You have given me a lot of happiness.

How do I display the data from the last to the first with a multidimensional array in php

So I'm new to coding and I was looking at arrays and I want to know if it's possible to display the last piece of data from an array first and the first piece of data to be last. This is the code I have.
<?php
$trans = array
(
array("10/3/22",1,54),
array("10/48/32", 54,54),
array("3/29/2018", 54, 128.84)
);
echo '<table border="1">';
echo '<tr><th>Date</th><th>Before Balance</th><th>After Balance</th></tr>';
foreach ($trans as $tran) {
echo '<tr>';
foreach( $tran as $data ) {
echo '<td>' . $data . '</td>';
}
echo '</tr>';
}
echo '</table>';
Use
array_reverse($array);
For more info http://php.net/manual/en/function.array-reverse.php
use array_reverse as follows in your forloop
foreach (array_reverse($trans) as $tran) {
echo '<tr>';
foreach( $tran as $data ) {
echo '<td>' . $data . '</td>';
}
echo '</tr>';
}

how to take foreach result in a table format

I want to take the result of foreach in a table format and that whole table in a variable.
Here is my model:
public function cron_job_seller(){
$this->db->select('*');
$this->db->from('wc_seller_products');
$query = $this->db->get();
$result = array();
foreach ($query->result() as $row){
$result[] = $row;
}
return $result;
}
and my controller is
public function cron_job(){
$this->load->model('home/Home_model');
$buyer = $this->Home_model->cron_job_buyer();
$this->load->library('email', array('mailtype'=>'html'));
$seller = $this->Home_model->cron_job_seller();
echo "<table>";
foreach($seller as $key=>$row) {
echo "<tr>";
foreach($row as $key2=>$row2){
echo "<td>" . $row2 . "</td>";
}
echo "</tr>";
}
echo "</table>";
gives o/p like this in table format
19 102 Rolex 65 Good 0000-00-00 fh ghf fgh ghf ghf gfh ghf ghf 56 56 download14.jpg 11/6/2016 19:03 2016-07-15 12:13:35 1 0
when i print $seller variable it gives
Array ( [0] => stdClass Object ( [id] => 19 [seller_id] => 102 [brand_name] => Rolex [model_no] => 65 [condition] => Good [date_purchase] => 0000-00-00 [case_size] => fh [case_shape] => ghf [case_material] => fgh [strap_type] => ghf [dial_colour] => ghf [water_resistance] => gfh [local_overseas] => ghf [warranty_period] => ghf [min_price] => 56 [sale_price] => 56 [photo] => download14.jpg [date] => 11/6/2016 19:03 [time] => 2016-07-15 12:13:35 [status] => 1 [login] => 0 [verified] => )
now i want 2 things in this:
1. that whole table in a single variable.
2. array keys like id, seller_id,brand_name as table heading
i really got confused what to do now and how to do...please help
public function cron_job() {
$this->load->model('home/Home_model');
$buyer = $this->Home_model->cron_job_buyer();
$this->load->library('email', array('mailtype'=>'html'));
$seller = $this->Home_model->cron_job_seller();
$theader = '';
$tbody = "<tbody>";
foreach($seller as $key => $row) {
$tbody .= "<tr>";
foreach($row as $key2 => $row2){
if (!$theader) {
$theader = array_keys($row2);
}
$tbody .= "<td>" . $row2 . "</td>";
}
$tbody .= "</tr>";
}
$tbody .= "</tbody>";
if (!empty($theader)) {
$theader = '<thead><th>' . implode('</th><th>', $theader) . '</th></thead>';
}
$table = '<table>'.$theader.$tbody.'</table>';
}
you don't need to worry much about it... It could be a solution. Just do like this in your controller:
$seller = $this->Home_model->cron_job_seller();
$table = "<table border='1'>";
$i=1;
foreach($seller as $key=>$row) { //you don't need to loop twice
if($i == 1){
$table.="<tr>";
$table .= "<th>".$key."</th>";
$table.="</tr>";
$i=0; //change value of $i so for next iteration the header will not print
}
$table .= "<tr>";
$table .= "<td>" . $row . "</td>";
$table.= "</tr>";
}
$table .= "</table>";
and also you need to return $query->result() from your model.
and now try print $table
using echo $table; it will print result as you want and now it is also set in a single variable so you can, and you set to $data['table'] = $table and end it to view, if you need.
You can just loop through the Array of Data from the DB and since each row is an array of Standard PHP Object (which contains the column names as keys), you can then extract the Column Names from the first row and then use it to construct the Table Header. Afterwards, you can just continue building Rows containing the actual Data you want. The Code below illustrates how:
<?php
function cron_job() {
$strOutput = "<table class='cron-tbl'>";
$this->load->model('home/Home_model');
$buyer = $this->Home_model->cron_job_buyer();
$this->load->library('email', array('mailtype' => 'html'));
$seller = $this->Home_model->cron_job_seller();
$cue = 0;
foreach ($seller as $key => $row) {
if($cue == 0){
// CREATE THE HEADER ROW:
$strOutput .= "<tr class='cron-head-row'>" . PHP_EOL;
foreach($row as $rowName=>$rowVal){
$strOutput .= "<th class='cron-head-cell'>{$rowName}</th>" . PHP_EOL;
}
$strOutput .= "</tr>" . PHP_EOL;
$strOutput .= "<tbody class='cron-body'>" . PHP_EOL;
}
// CREATE THE TABLE-BODY CELL
$strOutput .= "</tr>" . PHP_EOL;
foreach ($row as $rowKey => $data) {
$strOutput .= "<td class='cron-data-cell'>{$data}</td>" . PHP_EOL;
}
$strOutput .= "</tr>" . PHP_EOL;
$cue++;
}
$strOutput .= "</tbody>" . PHP_EOL;
$strOutput .= "</table>" . PHP_EOL;;
return $strOutput;
}
echo (cron_job());
Cheers & Good Luck...
Test it out yourself HERE.
You are doing correct but need some modifications
What you need to do is in you second foreach() loop you need to convert your object to array and take out the array keys array_keys($array) in a variable and print this keys to variable. As shown bellow.
$table = "<table border='1'>";
foreach($seller as $key=>$row) { //you don't need to loop twice
$table .="<tr>";
// creating a table heading
if($key === 0 ){
$cols = array_keys((array)$row); // Convert the object to array and take out all keys of array and assign to $cols variable
$table .="<th>".implode("</th><th>", $cols);
$table .="</th></tr><tr>";
}
// table heading end
$table .= '<td>'. implode('</td><td>', (array)$row). '</td>';
$table .= "</tr>";
}
$table .="</table>";
echo $table;
Try this way.
I guess html tag, body tag are missing. That's why didnot display table the way you want.
My suggestion is that for html part, it is better if put in view.
I have create view page cron_job_seller.php with bootstrap.
// Model - Change to this
public function cron_job_seller()
{
$this->db->select('*');
$this->db->from('wc_seller_products');
return $this->db->get();
}
// Controller
public function cron_job() {
$this->load->model('home/Home_model');
$this->load->library('email', array('mailtype'=>'html'));
$buyer = $this->Home_model->cron_job_buyer();
$seller = $this->Home_model->cron_job_seller();
$data['seller'] = $seller // Send data to View
// Create cron_job_seller.php file in Views Folder.
$this->load->view('cron_job_seller', $data);
}
// View cron_job_seller.php
<!DOCTYPE html>
<html lang="en">
<head>
<title>Sample Table</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap-theme.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<table class="table table-bordered">
<?php foreach($seller->result() as $row) { ?>
<tr>
<td><?php echo $row->colname_1; ?></td>
<td><?php echo $row->colname_2; ?></td>
<td><?php echo $row->colname_3; ?></td>
<td><?php echo $row->colname_4; ?></td>
</tr>
<?php } ?>
</table>
</div>
</body>
</html>

PHP While Loop/Foreach Loops

I have a question on a different way to wright this code because its not doing what I want it to do..
I am creating a forum list that will display the section under that category. Well this is the issue as you can see that I have an If () {}Else {} statement that is being used to put the information in that list I want. The problem is that I need to add a special class to the last section under that category that will be called last-tr. Now my issue that I have is all the information is making it to the screen but the class is only applied to the last row and now the last row of all the category's which is what i'm looking for.
So something like this,
Welcome Center
Introduce Yourself
Say Hello To our Admins (last-tr)
Game
COD
BF4 (last-tr)
Code
PHP
Java
PDO (last-tr)
but what my code is giving me is
Welcome Center
Introduce Yourself
Say Hello To our Admins
Game
COD
BF4
Code
PHP
Java
PDO (last-tr) <- Just that one.
Here is the code
<?php
include '../../core/init.php';
include '../../includes/head.php';
//Getting Categories under Welcome
$db = DB::getInstance();
$user = New User();
$forum = New Forum();
$list = '';
$category = $db->query('SELECT * FROM forum_categories');
foreach ($category->results() as $category) {
$list .= '<thead>';
$list .= '<tr>';
$list .= '<th class="titles">' . $category->title . '</th>';
$list .= '<th>Last Post</th>';
$list .= '<th>Topics</th>';
$list .= '<th>Replies</th>';
$list .= '</tr>';
$list .= '</thead>';
$list .= '<tbody>';
$sections = $db->query("SELECT * FROM forum_section WHERE category_id = '$category->id'");
foreach ($sections->results() as $section) {
$x = 0;
if ($x < $sections->count()) {
$list .= '<tr>';
$list .= '<td>';
$list .= '<a href="/category.php?id='. $section->id .'">';
$list .= '<img scr="/images/icons/iconmonstr/intro.png">';
$list .= '</a>';
$list .= '' . $section->title . '';
$list .= '<span>' . $section->desc . '</span>';
$list .= '</td>';
$list .= '<td> Nasty </td>';
$list .= '<td> 0 </td>';
$list .= '<td> 0 </td>';
$list .= '</tr>';
$x++;
}else {
$list .= '<tr class="last-tr">';
$list .= '<td>';
$list .= '' . $section->title . '';
$list .= '</td>';
$list .= '<td> Nasty </td>';
$list .= '<td> 0 </td>';
$list .= '<td> 0 </td>';
$list .= '</tr>';
}
}
$list .= '</tbody>';
}
?>
<link rel="stylesheet" href="/css/fourms.css">
<title>Forums</title>
</head>
<body>
<?php include '../../includes/header.php'; ?>
<section id="main_section">
<section id="main_content">
<div id="forum-section">
<table class="forumlist">
<?php echo $list; ?>
</table>
</div>
</section>
</section>
<?php include('../../includes/footer.php'); ?>
Your if-statement should be if ($x < $sections->count()-1) because the last index of an array is always count-1 due to starting at 0.
OR
You could also fix it here by starting $x at 1, since you are using a foreach with the counter on the side, so its not like you'll get an out of index error. In other words:
foreach ($sections->results() as $section) {
$x = 1;
if ($x < $sections->count()) {
...
$x++;
}else {
...
}
}
But going with the first option is probably more straight-forward.
You are testing against your overall class not the data within the class.
$sections->count() is counting all of the sections not the entries in teh one section you are dealing with.
You need to test the count of the singular section
So if you had
$sectionsAll = array(
sectionOne = array( 1, 2, 3),
sectionTwo = array( 1, 2, 3),
sectionThree = array( 1, 2, 3)
);
You are currently testing on $sectionsAll, you need to check against sectionOne, sectionTwo, sectionThree

Google Analytics API v3 how to extract values?

I'm a newbie at GA API so I have no clue how to extract results the correct way in this case.
e.g. I'm trying to extract avgTimeOnPage values based on filtering from ga:pagePath = ...
But each one is returning a single digit value on ga:pagePath.. so I'm thinking the ga:pagePath and ga:avgTimeOnPage results are not being displayed correctly. Maybe I'm not extracting the right way.
Anyone who can help would be greatly appreciated.
$ids = 'ga:123456789';
// $start_date $end_date already defined
$filter = 'ga:pagePath==/folder/somepage.html';
$metrics = 'ga:avgTimeOnPage';
$optParams = array('dimensions' => 'ga:pagePath', 'filters' => $filter);
$data = $service->data_ga->
get($ids, $start_date, $end_date, $metrics, $optParams);
foreach($data['totalsForAllResults'] as $rows) :
echo $rows['ga:pagePath']; // why returning a single digit value?
echo $rows['ga:avgTimeOnPage']; // also returns a single digit
endforeach;
$data['totalsForAllResults'] will return a single row that is the total row. You are looking for the values not the totals. so you should use:
foreach ($data->getRows() as $row) :
And then you can iterate $rows for every cell.
Check this full example:
private printDataTable(&$results) {
if (count($results->getRows()) > 0) {
$table .= '<table>';
// Print headers.
$table .= '<tr>';
foreach ($results->getColumnHeaders() as $header) {
$table .= '<th>' . $header->name . '</th>';
}
$table .= '</tr>';
// Print table rows.
foreach ($results->getRows() as $row) {
$table .= '<tr>';
foreach ($row as $cell) {
$table .= '<td>'
. htmlspecialchars($cell, ENT_NOQUOTES)
. '</td>';
}
$table .= '</tr>';
}
$table .= '</table>';
} else {
$table .= '<p>No Results Found.</p>';
}
print $table;
}
source: https://developers.google.com/analytics/devguides/reporting/core/v3/coreDevguide#working

Categories