I need help, have managed to get here with searching Google.. but stuck and cannot find a decent sample to complete my script.
A simple stock value system for intranet.
All i need is to calculate the Stock Value Row.
See red block on Image below
My Code - How do I calculate the Value with my script.. or any other example's I can look (links here or on the web) - MANY THANKS....
<?php try {
$conn = new PDO("mysql:host=$hostdb; dbname=$namedb", $userdb, $passdb);
$conn->exec("SET CHARACTER SET utf8");// Sets encoding UTF-8
$sql = "select * from stock_dry where stock_cat_id = 14 order by stock_id" ;
$result = $conn->query($sql);
if($result !== false) {
$cols = $result->columnCount();
foreach($result as $row) {
?>
<tr>
<td class="text-left"><?php echo $row['stock_id'];?></td>
<td class="text-left"><?php echo $row['stock_name'];?></td>
<td class="text-left"><?php echo $row['stock_count'];?></td>
<td class="text-left"><?php echo $row['stock_price'];?></td>
<td class="text-left">
<?php
$sum_total = $row['stock_count'] * $row['stock_price'];
echo $sum_total;
?>
</td>
<td class="text-left"><?php echo $row['stock_cat'];?></td>
</tr>
<?php
} } $conn = null; }
catch(PDOException $e) {
echo $e->getMessage();}
?>
You can simply add a variable before the loop like:
$tot = 0;
Then after the sum_total calc you add:
$tot += $sum_total;
I also would do a little change to sum_total (if you work with integers):
$sum_total = intval( $row['stock_count'] ) * intval( $row['stock_price'] );
or (if you work with floats):
$sum_total = floatval( $row['stock_count'] ) * floatval( $row['stock_price'] );
And with:
echo number_format( $sum_total, 2 );
You can print the float with 2 decimals.
Related
Couldn't find a specific answer to this so thought I'd ask. In short, I have a table that retrieves information from an API, based on data stored in my database and all I want to do is to get a total of certain, not all, columns from that table so that I can use them elsewhere on the site. As an example, let's use the Profit/Loss column and Total Divi. Do I have to somehow store the results as an array so that I can retrieve it elsewhere or is it something different?
<th>Profit/Loss</th>
<?php
for($x=0;$x<$y;$x++)
{?>
<tr>
<td class="input"><?php
if($pri[$x] > $lastprice[$x])
{
echo ($lastprice[$x]-$pri[$x]) * $vol[$x];
}
else if($pri[$x] < $lastprice[$x])
{
echo ($lastprice[$x]-$pri[$x]) * $vol[$x];
}
else
echo '0';
?></td>
<td><?php
$div = file_get_contents("https://api.iextrading.com/1.0/stock/market/batch?symbols=$symbol[$x]&types=stats&filter=dividendRate");
$div = json_decode($div,TRUE);
foreach($div as $divi => $value) {
echo $value['stats']['dividendRate'];
}
?></td>
<td><?php
$firstno = floatval($vol[$x]);
$secondno = floatval($value['stats']['dividendRate']);
$sum = $firstno * $secondno;
print ($sum);
?></td>
</tr>
<?php } ?>
So I only left the profit/loss row/column as well as dividend amount (2nd column) and dividend total, just so you can see how I get these numbers in the first place.
Your requirement is, you want to use the profit/loss and total dividend column data of each row at the later stage of your code. What you can do is, create an empty array before the outermost for loop, and in each iteration of the loop, append the pair where key would be $x and value would be an array of profit/loss and total dividend column data.
<th>Profit/Loss</th>
<?php
$arr = array();
for($x=0; $x < $y; $x++){
?>
<tr>
<td class="input">
<?php
$profitOrLoss = ($lastprice[$x]-$pri[$x]) * $vol[$x];
echo $profitOrLoss;
?>
</td>
<td>
<?php
$div = file_get_contents("https://api.iextrading.com/1.0/stock/market/batch?symbols=$symbol[$x]&types=stats&filter=dividendRate");
$div = json_decode($div,TRUE);
$sum = 0;
foreach($div as $divi => $value) {
echo $value['stats']['dividendRate'];
$sum += (floatval($vol[$x]) + floatval($value['stats']['dividendRate']));
}
?>
</td>
<td>
<?php
echo $sum;
?>
</td>
</tr>
<?php
$arr[$x] = array('profitOrLoss' => $profitOrLoss, 'sum' => $sum);
}
?>
Update(1):
Based on your comment, all I want is to add up all the rows in Profit/Loss column together as well as rows in Total Divi column together. the solution code would be like this:
<th>Profit/Loss</th>
<?php
$profitOrLossSum = 0;
$dividendRateSum = 0;
for($x=0; $x < $y; $x++){
?>
<tr>
<td class="input">
<?php
$profitOrLoss = ($lastprice[$x]-$pri[$x]) * $vol[$x];
$profitOrLossSum += $profitOrLoss;
echo $profitOrLoss;
?>
</td>
<td>
<?php
$div = file_get_contents("https://api.iextrading.com/1.0/stock/market/batch?symbols=$symbol[$x]&types=stats&filter=dividendRate");
$div = json_decode($div,TRUE);
$sum = 0;
foreach($div as $divi => $value) {
echo $value['stats']['dividendRate'];
$sum += (floatval($vol[$x]) + floatval($value['stats']['dividendRate']));
$dividendRateSum += floatval($value['stats']['dividendRate']);
}
?>
</td>
<td>
<?php
echo $sum;
?>
</td>
</tr>
<?php
}
$arr = array('profitOrLossSum' => $profitOrLossSum, 'dividendRateSum' => $dividendRateSum);
?>
Sidenote: If you want to see the complete array structure, do var_dump($arr);
I have a function that pulls data from mysql as follows;
function displayTrialBalance(){
require_once('Connections/mpcs_dbConn.php');
mysql_select_db($database_dbConn, $dbConn);
// declare query variables
$query_diff_empty = "SELECT Account_Code, sum(Amount) AS difference FROM journal2 GROUP BY Account_Code ORDER BY difference asc, Account_Code asc";
// check if user wants empty
// query DB
$amounts = mysql_query($query_diff_empty, $dbConn) or die(mysql_error());
$row_amounts = mysql_fetch_array($amounts);
$totalRows_users = mysql_num_rows($amounts);
if ($row_amounts){
function debit($arr){
return ($arr < 0);
}
function credit($arr){
return ($arr >= 0);
}
echo '<table align="center" border="0" bordercolor="#666666" cellpadding="5" cellspacing="3">
<tr class="tableTop">
<td>Account Code</td>
<td>Debit</td>
<td>Credit</td>';
do {
$diff = array($row_amounts['difference']);
echo '
</tr>
<tr class="tableButtom">
<td>'.$row_amounts['Account_Code'].'</td>
<td>';
foreach((array_filter($diff, "debit")) as $new){
echo abs($new).'.00';}
echo '</td>
<td>';
foreach((array_filter($diff, "credit")) as $new2){
echo $new2;
}
echo '</td>';
}while ($row_amounts = mysql_fetch_array($amounts));
echo '</tr>
</table>';
}
}
When i call displayTrialBalance() i get:
Account Code Debit Credit
13101 350000.00
22601 3000.00
22201 0.00
41101 3000.00
21201 40000.00
How can i sum the negative(Debit column) and positive(Credit column) numbers to get a total at the end the output table?
Also is it possible to sort the Account Code column in ascending order so that my expected output should be:
Account Code Debit Credit
13101 350000.00
22601 3000.00
21201 40000.00
22201 0.00
41101 3000.00
-----------------------------------
Total 353000.00 43000.00
I figured it out eventually, all i needed to do was to loop the array and collect the increments in another variable. Then echo the variable later in my table as the total.
function displayTrialBalance(){
require_once('Connections/mpcs_dbConn.php');
mysql_select_db($database_dbConn, $dbConn);
// declare query variables
$query_diff_empty = "SELECT Account_Code, sum(Amount) AS difference FROM journal2 GROUP BY Account_Code ORDER BY difference asc, Account_Code asc";
// check if user wants empty
// query DB
$amounts = mysql_query($query_diff_empty, $dbConn) or die(mysql_error());
$row_amounts = mysql_fetch_array($amounts);
$totalRows_users = mysql_num_rows($amounts);
if ($row_amounts){
function debit($arr){
return ($arr < 0);
}
function credit($arr){
return ($arr >= 0);
}
echo '<table align="center" border="0" bordercolor="#666666" cellpadding="5" cellspacing="3">
<tr class="tableTop">
<td>Account Code</td>
<td>Debit</td>
<td>Credit</td>';
// get total debit
foreach((array_filter($diff, "debit")) as $x){
$totalDebit += $x;
}
// get total credit
foreach((array_filter($diff, "credit")) as $y){
$totalCredit += $y;
}
do {
$diff = array($row_amounts['difference']);
echo '
</tr>
<tr class="tableButtom">
<td>'.$row_amounts['Account_Code'].'</td>
<td>';
foreach((array_filter($diff, "debit")) as $new){
echo abs($new).'.00';}
echo '</td>
<td>';
foreach((array_filter($diff, "credit")) as $new2){
echo $new2;
}
echo '</td>';
}while ($row_amounts = mysql_fetch_array($amounts));
echo '</tr>
<tr class="tableButtom">
<td>';
echo 'Total';
echo '</td>
<td>';
echo abs($totalDebit).'00';
echo '</td>
<td>';
echo $totalCredit.'00';
echo '</td>
</tr>
</table>';
}
}
I've been around for years on Stack but this is my first time posting. I'm working on a website (php + mysql) and the following problem is driving me absolutely nuts.
I have a table with 2 columns: Size and Amount. The table is generated by a basic php script simply outputting values stored in the database as rows in the table. Super basic, no fancy stuff there:
SELECT Size, Amount FROM database WHERE product = 'product123' ORDER BY Size ASC
The php echo outputs an html table displaying Size and the corresponding available packs (Amount).
Echo '<td>'.$record['size'].'</td><td>'.$record['amount'].'</td>'
Some Sizes are available in different Amounts, so therefore a particular Size can appear multiple times. Example:
Size | Amount
1 | 10
1 | 50
2 | 10
2+ | 10
3 | 40
3+ | 25
3+ | 40
4+ | 25
What I'm looking to achieve is that rows containing the same Size have the same background color. So it should alternate, grouped by Size, and this is irregular unfortunately. Example:
Size | Amount
1 | 10 < yellow
1 | 50 < yellow
2 | 10 < transparent
2+ | 10 < yellow
3 | 40 < transparent
3+ | 25 < yellow
3+ | 40 < yellow
4+ | 25 < transparent
So if the next Size is different from the preceding one, the row background color should change. This way a single Size is alternately highlighted as a group. Note that Size 2 and 2+ (same for 3 and 3+) are considered to be different sizes, hence the background color should change.
I can't figure out how to achieve this with php. The difficulty is that I can't use an evaluation based on odd/even since there sometimes is a "+" involved, making not all Sizes numeric values. Changing the naming scheme to get rid of that "+" is not an option unfortunately.
I was thinking of somehow having php check, while generating the table row by row, if the next outputted Size is identical to the preceding one. If yes: no change in bg-color. If no: change bg-color. However I can't figure out what the best way is to code something like this. Any pointers in the right direction are much appreciated.
Just a MCVE:
// your data
$records[] = array('size' => "1");
$records[] = array('size' => "1");
$records[] = array('size' => "2");
$records[] = array('size' => "2+");
$records[] = array('size' => "3");
$records[] = array('size' => "3+");
$records[] = array('size' => "3+");
$records[] = array('size' => "4");
$lastSize = $records[0]['size'];
$color = "yellow";
foreach ($records as $record) {
if ($lastSize != $record['size']) {
$lastSize = $record['size'];
if ($color == "yellow") $color = "transparent";
else $color = "yellow";
}
$lastSize == $record['size'];
echo $record['size'].' - '.$color.'<br>';
}
// OUTPUT:
// 1 - yellow
// 1 - yellow
// 2 - transparent
// 2+ - yellow
// 3 - transparent
// 3+ - yellow
// 3+ - yellow
// 4 - transparent
Ok, we'll start at the end. You probably want to put your color on the <tr>. The cleanest way to do it would be using css classes.
if ($newSize) {
echo '<tr class="tranparentRow">';
} else {
echo '<tr class="yellowRow">';
}
We'll figure out how to get the right value into $newSize in a moment. Next, we need the css for classes above, so make sure this is in your styles somewhere:
.transparentRow {
background-color: transparent;
}
.yellowRow {
background-color: yellow;
}
Ok, lets rip the + off the size:
$plainSize = trim($record['size'], '+')
Ok, we use that for comparison, using an ever changing $oldSize valiable. Here is a full, functional, block:
$oldSize = 0;
foreach($whatever as $record) {
$plainSize = trim($record['size'], '+')
if ($plainSize == $oldSize) {
$newSize = false;
} else {
$newSize = true;
}
$oldSize = $plainSize;
if ($newSize) {
echo '<tr class="tranparentRow">';
} else {
echo '<tr class="yellowRow">';
}
echo '<td>'.$record['size'].'</td><td>'.$record['amount'].'</td>';
echo '</td>';
}
Some cleanup can lead to this:
$oldSize = 0;
foreach($whatever as $record) {
$plainSize = trim($record['size'], '+')
if ($plainSize == $oldSize) {
echo '<tr class="tranparentRow">';
} else {
echo '<tr class="yellowRow">';
}
$oldSize = $plainSize;
echo '<td>'.$record['size'].'</td><td>'.$record['amount'].'</td>';
echo '</td>';
}
I hope that helped not just with this problem, but with an example of how you can approach many other problems. Start at the end, work your way back.
As my comment suggested, use a double foreach() + implode() (and yet another solution):
<?php
$array[] = array("size"=>1,"amount"=>50);
$array[] = array("size"=>2,"amount"=>10);
$array[] = array("size"=>"2+","amount"=>10);
$array[] = array("size"=>3,"amount"=>40);
$array[] = array("size"=>"3+","amount"=>25);
$array[] = array("size"=>"3+","amount"=>40);
$array[] = array("size"=>"3+","amount"=>25);
$array[] = array("size"=>'4+',"amount"=>30);
// Sort by size
foreach($array as $row) {
$new[$row['size']][] = $row['amount'];
}
?>
<table>
<?php
$i = 0;
// Loop through the sorted groups
foreach($new as $size => $amts) {
// Determine odd or even
$color = ($i % 2 == 0)? "yellow":"transparent";
?> <tr>
<td class="<?php echo $color; ?>"><?php echo $size; ?></td>
<td class="<?php echo $color; ?>"><?php echo implode("</td>".PHP_EOL."</tr>".PHP_EOL."<tr>".PHP_EOL.'<td class="'.$color.'">'.$size.'</td><td class="'.$color.'">',$amts); ?></td>
</tr>
<?php $i++;
}
?>
</table>
You can do this using php sessions like this
session_start();
$_SESSION["pre_val"]='not set';
$_SESSION["pre_class"]='transparent';
//in your loop for showing table
//your loop starts
if($_SESSION["pre_val"]==$record['size']){
$suitable_class=$_SESSION["pre_class"];
}
else{
if($_SESSION["pre_class"]=='yellow'){$suitable_class='transparent';}
else{$suitable_class='yellow';}
}
//setting current values to session
$_SESSION["pre_class"] = $suitable_class;
$_SESSION["pre_val"] = $record['size'];
Echo '<tr class="$suitable_class"><td>'.$record['size'].'</td><td>'.$record['amount'].'</td></tr>';
//your loop ends
in your css
.yellow{background-color:yellow;}
.transparent{ background-color: rgba(255, 0, 0, 0.5);}
hope this solve your problem
Some for loop fun while printing out the table
$rows = array(
array("size"=>"1" ,"amount"=>"10"),
array("size"=>"1" ,"amount"=>"50"),
array("size"=>"2" ,"amount"=>"10"),
array("size"=>"2+","amount"=>"10"),
array("size"=>"3" ,"amount"=>"40"),
array("size"=>"3+","amount"=>"25"),
array("size"=>"3+","amount"=>"40"),
array("size"=>"4+","amount"=>"25")
);
echo "
<table>
<thead>
<tr><th>Size</th><th>Amount</th></tr>
</thead>
<tbody>";
$bgColors = ['transparent','yellow'];
$bgColor = 0;
echo "
<tr>
<td class='" . $bgColors[$bgColor] . "'>" . $rows[0]["size"] . "</td><td>" . $rows[0]["amount"] . "</td>
</tr>";
for($i = 1, $max = count($rows), $lastSize = $rows[0]; $i < $max; $lastSize = $rows[$i], $i++) {
if($rows[$i]["size"] !== $lastSize["size"])
$bgColor = ($bgColor + 1) % 2;
echo "
<tr>
<td style='background-color:" . $bgColors[$bgColor] . "'>" . $rows[$i]["size"] . "</td><td>" . $rows[$i]["amount"] . "</td>
</tr>";
}
echo "
</tbody>
</table>";
And an unasked for JS solution (assuming you've printed out the table as usual)
var rows = document.querySelectorAll('#sizeTable tbody td[name=size]');
var bgColors = ['transparent','yellow'];
var bgColor = 0;
for(var i = 1, lastSize = rows[0], max = rows.length; i < max; lastSize = rows[i],i++) {
if(rows[i].innerHTML !== lastSize.innerHTML) {
bgColor = (bgColor + 1) % 2;
}
rows[i].style['background-color'] = bgColors[bgColor];
}
you can keep the current size on a variable and if it changes you can change the color.
<html>
<head><title> Sample - Menukz </title></head>
<body>
<?php
/* Sample data array with size and amount */
$product['product123'] = array
(
array("size"=>"1", "amount"=>10),
array("size"=>"1", "amount"=>50),
array("size"=>"2", "amount"=>10),
array("size"=>"2+", "amount"=>10),
array("size"=>"3", "amount"=>40),
array("size"=>"3+", "amount"=>25),
array("size"=>"3+", "amount"=>40),
array("size"=>"4+", "amount"=>25)
);
$pre_size=0;
$pre_init=1;
echo "<table>";
foreach($product['product123'] as $row)
{
echo "<tr>";
/* Initialize */
if(strcmp($pre_size, $row['size']) !== 0 && $pre_init ===1)
{
$pre_size = $row['size'];
$pre_init = 0;
}
/* Change track */
if (strcmp($pre_size, $row['size']) !== 0 && $pre_init ===0)
{
echo "<td>Changed ... </td><td>". $row['size'] . "</td><td>" . $row['amount'] . "</td>";
$pre_size = $row['size'];
}
else
{
echo "<td>Not Changed ... </td><td>". $row['size'] . "</td><td>" . $row['amount'] . "</td>";
}
echo "</tr>";
}
?>
</body>
</html>
Thanks all for the proposed solutions. Berriel's MCVE works like a charm! However Stack doesn't let me +1 the answer yet.
I have one additional question:
I also have a second table in which the output of the first column can be any article code consisting of 10 chars limited to [a-z][0-9]. Since there is no predefined scheme such as in the Size table, I can't hardcode/predict any output like in most of the proposed solutions. However I still want to color the rows it in the same way described in my opening post.
I am not familiar with Stored Procedures or PDO in mysql. Is there any way to work around arrays with predefined content and still achieve the color grouping of rows with the same article code?
You can accomplish this using a nested repeat region.
First select your product by group WHERE product = 'product123' GROUP BY size
<?php
require ('conn.php');
try {
$prod = 'product123';
$sql = "SELECT * FROM sizes WHERE product=:prod GROUP BY size";
$query = $conn->prepare($sql);
$query->bindValue(':prod', $prod, PDO::PARAM_INT);
$query->execute();
$row = $query->fetch(PDO::FETCH_ASSOC);
$totalRows = $query->rowCount();
} catch (PDOException $e) {
die('failed!');
}
?>
Then get all the products in each group ordered by amount inside a nested repeat region.
Each "grouped row" will alternate colors.
<table width="200" border="0" cellspacing="0" cellpadding="5">
<tr>
<td>Size</td>
<td>Amount</td>
</tr>
<?php
$i = 0;
do {
$i = $i + 1;
if ($i % 2 == 0){
echo '<tr bgcolor=#E4E4E4><td colspan="2">';
} else {
echo '<tr bgcolor=#EEEEEE><td colspan="2">';
}
try {
$group = $row['size'];
$sql = "SELECT * FROM sizes WHERE size=:group ORDER BY amount ASC";
$nested = $conn->prepare($sql);
$nested->bindValue(':group', $group, PDO::PARAM_INT);
$nested->execute();
$row_nested = $nested->fetch(PDO::FETCH_ASSOC);
$totalRows_nested = $nested->rowCount();
} catch (PDOException $e) {
die('nested failed');
}
echo '<table border="0" cellpadding="0" cellspacing="0" width="200">';
do {
echo '<tr><td width="100">'.$row_nested['size'].'</td><td width="100">'.$row_nested['amount'].'</td></tr>';
} while ($row_nested = $nested->fetch(PDO::FETCH_ASSOC));
echo '</table>';
echo '</td></tr>';
} while ($row = $query->fetch(PDO::FETCH_ASSOC));
?>
</table>
What I want:- I want to calculate the total working hours of my employees based on the working hours of multiple days.
My problem the total working hours ($total_hours) is not working.
My Model
class Attendence extends AppModel {
function add($data){
if (!empty($data)) {
$this->create();
if($this->save($data)) {
return true ;
}
}
}
function fetchdata() {
return $this->find('all', array('conditions' => array('Attendence.date' > '2014-04-01',
'AND' => array('Attendences.date' < '2014-04-21'),
)));
}
}
My Controller
class EmployeesController extends AppController {
public $uses = array('Employee', 'Attendence', 'InsertDate');
public function add()
{
if($this->Employee->add($this->request->data)==true){
$this->redirect(array('action'=>'index'));
}
}
public function index(){
$this->set('employees',$this->Employee->Fetch());
$this->set('attendence',$this->Attendence->fetchdata());
$this->set('dates',$this->InsertDate->fetchdate());
}
}
My View
<div class="index">
<table>
<thead>
<th>Num</th>
<th>Employee</th>
<th>Salary/Hour</th>
<th>Start Date</th>
<th>End Date</th>
<th>Total Hour</th>
<th>Total Salary</th>
</thead>
<?php
$id = 0;
foreach($employees as $e):?>
<? $id++ ?>
<tr>
<td><?php echo $e{'Employee'}{'id'} ?></td>
<td><?php echo $e['Employee']['firstname'], $e['Employee']['lastname'] ?></td>
<td style="text-align:center"><?php echo $e['Employee']['salary'] ?></td>'
<?php foreach($dates as $d):?>
<td><?php echo $d['InsertDate']['start_date'] ?></td>
<td><?php echo $d['InsertDate']['end_date'] ?></td>
<?php
$total_hours = 0;
foreach ($attendence as $et){
$ts1 = strtotime($et['Attendence']['in_time']);
$ts2 = strtotime($et['Attendence']['out_time']);
$diff = abs($ts1 - $ts2) / 3600;
$total_hours += number_format($diff,2);
}
//Total hours
echo '<td style="text-align:center">'.$total_hours.'</td>';
//Total Salary
echo '<td style="text-align:center">'.$total_hours*$e['Employee']['salary'].'</td>';
?>
<?php endforeach; ?>
<?php endforeach; ?>
</tr>
</table>
</div>
A programmer friend of mine gave me a solution. But I dont know how to implement in CAKEPHP
I am updating the solution also
Look at here :
$total_hours = 0;
foreach ($attendence as $et){
$ts1 = strtotime($et['Attendence']['in_time']);
$ts2 = strtotime($et['Attendence']['out_time']);
$diff = abs($ts1 - $ts2) / 3600;
$total_hours += number_format($diff,2);
}
The code shows you that there is an array. the array contains (attendance id and in_time and out_time in each point).
The Important thing is you should check how you fill this array.
In the above foreach that you generate the table by $employees array , you have the (employee_id) wich name (id) here
So you should write a new query in your view!!!In the middle of your first foreach and before second foreach
before this line :
$total_hours = 0
You have to write a query and fetch data from DB like this :
//SELECT * FROM attendences
WHERE attendences.date > '2014-04-23' AND attendences.date < '2014-04-30'
AND id=$e['Employee']['id'] // is your employee_id in your first array.
So when you fetched data , You have a new array named "$attendence"
Then , your second foreach(which calculates the salary and total hours) should work correctly
I'm building an analytics tool for some Facebook pages where I can view page information and statistics.
The problem is that it takes a long time to load the data using FQL, almost 50 seconds to load the page fully. The problem is that it needs to request a query for each day when I want to know all the new likes within a month and then count them all up.
These are the functions I'm using:
function getmetrics($objectid, $metrics, $end_time, $period){
global $facebook;
$fql = "SELECT value FROM insights WHERE object_id=$objectid AND metric='$metrics' AND end_time=end_time_date('$end_time') AND period=$period";
$response = $facebook->api(array(
'method' => 'fql.query',
'query' =>$fql,
));
if (!empty($response)){
return $response[0]['value'];
}
else{
return "no results found";
}
}
function getdailymetrics($objectid, $metrics, $end_time , $days ){
global $facebook;
$total = 0;
do {
$amount = getmetrics($objectid, $metrics, $end_time, '86400');
$total += $amount;
$pieces = explode("-", $end_time);
$end_time = date("Y-m-d", mktime(0, 0, 0, date($pieces[1]),date($pieces[2])-1,date($pieces[0])));
$days--;
} while($days > 1);
return $total;
}
On the front end:
<table>
<tr>
<td>Total likes</td>
<?php
$like1 = getmetrics($samsung, 'page_fans', '2012-01-29', '0');
$like2 = getmetrics($samsung, 'page_fans', '2012-02-26', '0');
$likep = round((($like2/$like1)-1)*100, 2);
?>
<td><?php echo $like1; ?></td>
<td><?php echo $likep; ?>%</td>
<td><?php echo $like2; ?></td>
</tr>
<tr>
<td>New Likes</td>
<?php
$newlikes1 = getdailymetrics($samsung, 'page_fan_adds', '2012-01-29', '28');
$newlikes2 = getdailymetrics($samsung, 'page_fan_adds', '2012-02-26', '28');
$newlikep = round((($newlikes2/$newlikes1)-1)*100, 2);
?>
<td><?php echo $newlikes1; ?></td>
<td><?php echo $newlikep; ?>%</td>
<td><?php echo $newlikes2; ?></td>
</tr>
<tr>
<td>Daily New Likes</td>
<td><?php echo round($newlikes1/28); ?></td>
<td><?php echo $newlikep; ?>%</td>
<td><?php echo round($newlikes2/28); ?></td>
</tr>
</table>
Is there a way to speed this up or is there a more efficient way?
You can try to reduce the amount of requests in two ways. First, you can use batch requests to send up to 50 queries to FB in one request. Also you can try to change your query, so that it would request insights for several days at once, like end_time in (values_list).
Also you could do some caching of the results.
And, though it depends on your certain case, maybe you could consider pulling insights with daemon (if you have the objects to pull data for), and storing it in the database.
I resolved the problem with a different method of fetching the data, using this function:
function getfromuntil($objectid, $metric, $start_time, $end_time){
global $facebook;
try {
$start_time = $timestamp = strtotime($start_time);
$end_time = $timestamp = strtotime($end_time);
$response = $facebook->api('/'.$objectid.'/insights/'.$metric.'?since='.$start_time.'&until='.$end_time);
} catch (FacebookApiException $e){
error_log($e);
}
$total = 0;
foreach ($response['data'][0]['values'] as $value) {
$total += $value['value'];
}
return $total;
}