Laravel api page number 2 and above of pagination issue - pagination

i am trying to customize laravel pagination to fix this issue:
{
"current_page": 2,
"data": {
"10": {},
"11": {},
}
i want the result to be like this:
{
"current_page": 1,
"data": [
{},
{},
}
when i use the whole collection it works good, but if get part of the collection using (where), this issue appear for me.
this coming script of code has been used in the AppServiceProvider boot method:
Collection::macro('paginate', function($perPage, $total = null, $page = null, $pageName = 'page') {
$page = $page ?: LengthAwarePaginator::resolveCurrentPage($pageName);
return new LengthAwarePaginator(
$this->forPage($page, $perPage),
$total ?: $this->count(),
$perPage,
$page,
[
'path' => LengthAwarePaginator::resolveCurrentPath(),
'pageName' => $pageName,
]
);
});

i found the solution for my issue by replacing this code:
Collection::macro('paginate', function($perPage, $total = null, $page = null, $pageName = 'page') {
$page = $page ?: LengthAwarePaginator::resolveCurrentPage($pageName);
return new LengthAwarePaginator(
$this->forPage($page, $perPage),
$total ?: $this->count(),
$perPage,
$page,
[
'path' => LengthAwarePaginator::resolveCurrentPath(),
'pageName' => $pageName,
]
);
});
with this one:
if (!Collection::hasMacro('paginate')) {
Collection::macro('paginate', function ($perPage = 15, $page = null, $options = []) {
$page = $page ?: (Paginator::resolveCurrentPage() ?: 1);
return (new LengthAwarePaginator( $this->forPage($page, $perPage)->values()->all(), $this->count(), $perPage, $page, $options))->withPath('');
});
}
AppServiceProvider boot method.

Related

Maatwebsite/Laravel-Excel View format

I am loading Laravel view and exporting as Excel using Maatwebsite/Laravel-Excel but my data showing as text but i need to make it as decimal, number. how can i do this. I have already read the documentation but there i cant find solution.
$fileName = 'Receipt Register : From '.date('d-m-Y', strtotime($date_from)).' To '.date('d-m-Y', strtotime($date_to)).($itemDetails ? ' For Item '.$itemDetails->item_code : "");
Excel::create($fileName, function( $excel) use($date_from, $date_to, $request) {
$excel->sheet('Receipt-Register', function($sheet) use($date_from, $date_to, $request) {
$itemDetails = [];
$itemFilterData = [];
$result = Ledger::where('receive_quantity', '!=', NULL)
->where('receive_quantity', ">", 0)
->orderBy('date', 'ASC')
->orderBy('mrn_number',"ASC")
->whereNotNull('mrn_number')
->whereNotNull('mrn_id')
->orderBy('id', "ASC")
->with('department', 'item', 'itemGroup', 'mrn')
->has('mrn', ">", 0);
if($request->date_from) {
$date_from = date('Y-m-d', strtotime($request->date_from));
$result = $result->whereDate('date', '>=', $date_from);
}
if($request->date_to) {
$date_to = date('Y-m-d', strtotime($request->date_to));
$result = $result->whereDate('date', '<=', $date_to);
}
if($request->item_id){
$result = $result->where('item_id', '=', $request->item_id);
$itemDetails = Item::find($request->item_id);
}
$results = $result->get();
$sheet->loadView('export_view',[
'results' => $results,
'date_from' => $date_from,
'date_to' => $date_to,
'itemFilterData' => $itemFilterData
]);
});
})->download('xlsx');

Notice: Undefined index: Page in C:\xampp\htdocs\admin\achive\nur.php on line 16

First page showing:
Notice: Undefined index: Page in C:\xampp\htdocs\admin\achive\nur.php on line 16
Notice: Undefined index: Page in C:\xampp\htdocs\admin\achive\nur.php on line 17.....
<?php
if($_GET["txtKeyword"] != "")
{
$objConnect = mysql_connect("localhost","root","") or die(mysql_error());
$objDB = mysql_select_db("gnnursury");
// Search By Name or Email
$strSQL = "select #rownum:=#rownum+1 rank,stid,roll,tmark,name from mark, (SELECT #rownum:=0) r WHERE (year LIKE '%".$_GET["txtKeyword"]."%')";
$objQuery = mysql_query($strSQL) or die ("Error Query [".$strSQL."]");
$Num_Rows = mysql_num_rows($objQuery);
$Per_Page = 6; // Per Page
$Page = $_GET["Page"];
if(!$_GET["Page"])
{
$Page=1;
}
$Prev_Page = $Page-1;
$Next_Page = $Page+1;
$Page_Start = (($Per_Page*$Page)-$Per_Page);
if($Num_Rows<=$Per_Page)
{
$Num_Pages =1;
}
else if(($Num_Rows % $Per_Page)==0)
{
$Num_Pages =($Num_Rows/$Per_Page) ;
}
else
{
$Num_Pages =($Num_Rows/$Per_Page)+1;
$Num_Pages = (int)$Num_Pages;
}
$strSQL .="order by tmark ASC LIMIT $Page_Start , $Per_Page";
$objQuery = mysql_query($strSQL);
?>
You are not passing a
GET parameter Page
and you are directly referencing it in line 17 $Page = $_GET["Page"];
Ideally for this easy fix will be
if(!$_GET["Page"])
{
$Page=1;
}
else{
$Page = $_GET["Page"];
}
Hope it helps
Happy Coding !!!
You can use php function isset to check a argument "Page" is set.
if (isset($_GET['Page'])) {
$Page = $_GET['Page'];
} else {
$Page = 1
}
You did not pass any "Page" parameter. You can change the code to.
if(!isset($_GET["Page"]))
{
$Page=1;
}
Update these lines
$Page = $_GET["Page"];
if(!$_GET["Page"])
{
$Page=1;
}
With
if(isset($_GET["Page"] && !empty($_GET['Page'])))
{
$Page=$_GET["Page"];;
}else{
$Page=1;
}

Joomla 2.5 component : Invalid controller: name='', format='raw'

im developing a custom joomla 2.5 component integrating jqGrid.
im setting up a controller task to handle (update mysql record) data sent from jqGrid postData
var grid = jQuery(\"#list\");
grid.jqGrid({
onSelectRow: function(id){
$('#list').editRow(id, true);
},
url: '/index.php?option=com_nutraidev&view=products&format=raw',
datatype: 'json',
mtype: 'GET',
colNames: [...],
rowNum: 25,
rowList: [5, 10, 20, 50],
height: 'auto',
pager: '#pager',
loadonce: true,
sortname: 'ID',
viewrecords: true,
direction:'RTL',
autowidth: true,
sortorder: \"desc\",
caption: 'abc',
width: '70%',
editurl:'/index.php?option=com_nutraidev&view=products&task=Products.save&token=". JUtility::getToken() ."=1',
postData: {'code':\" \",....},
.....
this is the url which makes the request
/index.php?option=com_nutraidev&view=products&task=Products.save&token=". JUtility::getToken() ."=1&format=raw
im getting:
error 500
Invalid controller: name='products', format='raw'
tried it from the browser with the actual token - same result.
here is the important part of my code:
com_nutraidev
- controllers
- products.php
require_once JPATH_COMPONENT.'/controller.php';
class NutraidevControllerProducts extends NutraidevController
{
public function &getModel($name = 'Products', $prefix = 'NutraidevModel')
{
$model = parent::getModel($name, $prefix, array('ignore_request' => true));
return $model;
}
public function save()
{
// Check for request forgeries.
JSession::checkToken() or jexit(JText::_('JINVALID_TOKEN'));
// Initialise variables.
$app = JFactory::getApplication();
$model = $this->getModel('Products', 'NutraidevModel');
$data = JRequest::get('get');
// Attempt to save the data.
$return = $model->updItem($data);
}
}
com_nutraidev
- models
- products.php
jimport('joomla.application.component.modellist');
class NutraidevModelProducts extends JModelList {
public function __construct($config = array()) {
parent::__construct($config);
}
public function updItem($data)
{
// set the variables from the passed data
$code = $data['code'];
$name = $data['name'];
// set the data into a query to update the record
$db = $this->getDbo();
$query = $db->getQuery(true);
$query->clear();
$query->update(' #__product ');
$query->set(' name = '.$db->Quote($name) );
$query->where(' code = ' . (int) $code );
$db->setQuery((string)$query);
if (!$db->query()) {
JError::raiseError(500, $db->getErrorMsg());
return false;
} else {
return true;
}
}
}
com_nutraidev
- views
- products
- view.raw.php
jimport('joomla.application.component.view');
class NutraidevViewProducts extends JView
{
/**
* Display the view
*/
public function display($tpl = null)
{
$app = JFactory::getApplication();
$document = JFactory::getDocument();
// Get data from the model
$items = $this->get('Items');
$this->state = $this->get('State');
$this->params = $app->getParams('com_nutraidev');
// Check for errors.
if (count($errors = $this->get('Errors'))) {;
throw new Exception(implode("\n", $errors));
}
// Assign data to the view
$response->page = 1;//JRequest::getVar('page');
$response->total = 1;//JRequest::getVar('total');
$response->records = count($items);
$i=0;
for ($i = 0; $i < count($items); ++$i) {
$response->rows[$i]['id'] = intval($items[$i]->code); //id
$response->rows[$i]['cell'] = array($items[$i]->code,
$items[$i]->name
);
}
echo json_encode($response);
jexit();
}
public function save($tpl = null)
{
echo "test";
jexit();
}
}
looking at other questions that had the similar issue i double checked my
administrator/components/nutraidev/nutraidev.xml
and made sure
<files folder="site">
<filename>controller.php</filename>
was there.
what could be the reason im getting this error ? i tried it also with view.json.php
and got the same result. thanks

Kohana 3.2, displaying errors in the form

I'd like to display errors on my form, highlighting the fields which have errors, and displaying the error text next to the field. If there's no elegant way to display next to each field, above would be fine.
I've found examples from earlier versions, but the API has seemed to change and they do not work for 3.2.
It's just a project I'm learning Kohana with, so it's not critical. I just want to know the "kohana" way of handling this problem.
In my controller, I have this:
if (isset($_POST) && Valid::not_empty($_POST))
{
$post = Validation::factory($_POST)
->rule('zipcode', 'not_empty'));
if ($post->check()) {
$errors = $post->errors('zipcode');
}
}
$this->template->content = View::factory('myview', $data)
->bind('errors', $errors);
And here is my form in 'myview.php':
<?php echo Form::open(); ?>
<dl>
<dt><?php echo Form::label('zipcode', 'Zip Code') ?></dt>
<dd><?php echo Form::input('zipcode') ?></dd>
</dl>
<p><?php echo Form::submit(NULL, 'Get Records'); ?></p>
<?php echo Form::close(); ?>
I've taken the approach of extending the Form helper class to add an 'error' class name on the form fields, as well as showing the error message in the field label.
<?php defined('SYSPATH') or die('No direct script access.');
class Form extends Kohana_Form {
private static function attributes($name, & $attributes = NULL, $errors = NULL)
{
// Set the id attribute
if (!isset($attributes['id']))
{
$attributes['id'] = $name;
}
if ($errors !== NULL)
{
// Merge in external validation errors.
$errors = array_merge($errors, (isset($errors['_external']) ? $errors['_external'] : array()));
// Set the error classname
if (isset($errors[$name]))
{
$attributes['class'] = trim( (string) #$attributes['class'].' error-field');
}
}
}
public static function input($name, $value = NULL, array $attributes = NULL, array $errors = NULL)
{
static::attributes($name, $attributes, $errors);
return parent::input($name, $value, $attributes);
}
public static function select($name, array $options = NULL, $selected = NULL, array $attributes = NULL, array $errors = NULL)
{
static::attributes($name, $attributes, $errors);
return parent::select($name, $options, $selected, $attributes);
}
public static function password($name, $value = NULL, array $attributes = NULL, array $errors = NULL)
{
static::attributes($name, $attributes, $errors);
return parent::password($name, $value, $attributes);
}
public static function textarea($name, $body = '', array $attributes = NULL, $double_encode = TRUE, array $errors = NULL)
{
static::attributes($name, $attributes, $errors);
return parent::textarea($name, $body, $attributes, $double_encode);
}
public static function file($name, array $attributes = NULL, array $errors = NULL)
{
static::attributes($name, $attributes, $errors);
return parent::file($name, $attributes);
}
public static function label($input, $text = NULL, array $attributes = NULL, array $errors = NULL, $view = 'messages/label_error')
{
if ($errors !== NULL)
{
// Merge in external validation errors.
$errors = array_merge($errors, (isset($errors['_external']) ? $errors['_external'] : array()));
// Use the label_error view to append an error message to the label
if (isset($errors[$input]))
{
$text .= View::factory($view)->bind('error', $errors[$input]);
}
}
return parent::label($input, $text, $attributes);
}
}
You then pass in the $errors array into the label and field helper methods:
<?php echo
Form::label('username', 'Username', NULL, $errors),
Form::input('username', $user->username, NULL, $errors);
?>
This idea was suggested on the Kohana forums but I've struggled to find the original thread. Anyway, I've found this approach works best for me.
[edit] View an example of this approach in action here: http://kohana3.badsyntax.co/contact (submit the form)
This is some sample code I have used for a personal experiment with Kohana forms. It is part of a contact form. This should work for you.
The code below shows a contact form. After a user submits the form, it gives feedback (failed + errors / succeed).
if (isset($errors) && count($errors) > 0)
{
echo '<ul>';
foreach ($errors as $error)
{
echo '<li>' . $error . '</li>';
}
echo '</ul>';
}
// form
echo Form::open(null);
// fields
echo Form::label('firstname') . Form::input('firstname', null, array('id' => 'firstname')) . '<br />';
echo Form::label('email') . Form::input('email', null, array('id' => 'email')) . '<br />';
echo Form::label('message') . Form::textarea('message', '', array('id' => 'message')) . '<br />';
// submit
echo Form::submit('submit', 'Send message');
echo Form::close();
In the controller, I validate the form and assign the error- and success messages to the view.
public function action_index()
{
// make view
$view = View::factory('pages/contact')
->bind('post', $post)
->bind('errors', $errors)
->bind('success', $success);
// check if form is submitted
if ($_POST)
{
// trim fields
$post = array_map('trim', $_POST);
$post = Validation::factory($_POST)
->rules('firstname', array(
array('not_empty'),
array('min_length', array(':value', '2'))
))
->rules('email', array(
array('not_empty'),
array('email')
))
->rule('message', 'not_empty');
if ($post->check())
{
$success[] = 'Thank you for your message!';
}
else
{
$errors = $post->errors('contact');
}
}
// view
$this->response->body($view);
}
I hope this helps!

How to retrieve all the reviews publicly available for an extension in the Google Chrome webstore - JSON & cross-domain issue

I'm interested in gathering/scraping data about the reviews earned by popular extensions available in the Chrome Webstore.
In particular, I need to retrieve the number of total reviews left for a specific extension and then retrieve all the reviews publicly available for this addon. My problem is the following: I cannot write a standard PHP Curl scraper since the data I'm interested in is available through json requests, in particular, I need to call:
https://chrome.google.com/reviews/components for the number of
reviews ('numRatings')
https://chrome.google.com/reviews/json/search
for the reviews ("comment")
I tried to write this:
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
function getReviews(extensionId, callback) {
var entities = [{'url' : 'http://chrome.google.com/extensions/permalink?id=' + extensionId}];
var param = {"searchSpecs":[{"requireComment":true,"entities": entities,"groups":["public_comment"],"matchExtraGroups":true,"sortBy":"quality","startIndex":10,"numResults":10,"includeNickNames":true}],"applicationId":94};
$.ajax({
type: 'POST',
url: 'https://chrome.google.com/reviews/json/search',
contentType: 'application/xml',
xhrFields: {withCredentials: true },
dataType: 'json',
data: 'req=' + JSON.stringify(param) + '&requestSource=widget'
}).success(callback);
}
</script>
<script type="text/javascript">
$(document).ready(getReviews('gighmmpiobklfepjocnamgkkbiglidom', function(reviews) { console.log(reviews); }));
</script>
I'm not very keen in jQuery/JSON(-P) and the code above is certainly wrong.
My questions are as follows:
How to bypass the same-domain policy? I tried YQL without success...
How to format my url/'data' to only retrieve the number of
reviews ('numRatings') on chrome.google.com/reviews/components and the reviews ('comments') on chrome.google.com/reviews/json/search for a specific extension identified by its id, e.g. gighmmpiobklfepjocnamgkkbiglidom?
I already accomplished this kind of scraping for popular Mozilla Addons using PHP and gathered the data I needed using a standard curl/XPath.
Thanks for your help!
1) The easiest way would be to create a Chrome extension;
2) See https://github.com/xpressyoo/MyExtensions
[...]
getComments : function() {
var entities = [];
//each(Ext.extensions, function(data, id) {
entities.push({'url' : 'http://chrome.google.com/extensions/permalink?id=' + this.hash});
//});
Ext.XHR['comments'] = new Ajax({
'method' : 'POST',
'encodeURI' : false, // Needed
'url' : 'https://chrome.google.com/reviews/json/search',
'headers' : {
'Content-type' : 'application/xml'
},
'parameters' : {
'req' : JSON.stringify({'searchSpecs' : [{'entities' : entities, 'groups' : ['public_comment'], 'matchExtraGroups' : true,"sortBy":"quality", 'startIndex' : 0, 'numResults' : 80, 'includeNickNames' : true}], 'applicationId' : 94 }) + '&requestSource=widget'
},
'onSuccess' : function(xhr) {
var json = xhr.responseJSON;
if(json && json.searchResults ) {
this.comments = {
'total' : Number(json.searchResults[0].numAnnotations.toString().replace(/,/, '').toInt()),
'latest' : json.searchResults[0].annotations ? json.searchResults[0].annotations[0] :{},
'previous' : this.comments.total || null,
'latestPrevious' : $merge(this.comments.latest) || null,
'new' : this.comments['new'] || false
}
Ext.XHR['comments'] = null;
}
}.bind(this)
}).send();
return this;
},
[...]
and
var nbreviews = this.comments.total; //The number of reviews
var latestcomment = (this.comments.latest0 && this.comments.latest0.comment ? this.comments.latest0.comment.replace(/\n/gi, '') : '');// get the latest comment
var nthcomment = (this.comments.latestn && this.comments.latestn.comment ? this.comments.latestn.comment.replace(/\n/gi, '') : '');//Get the nth comment
where:
'latestn' : json.searchResults[0].annotations ? json.searchResults[0].annotations[n] :{},
Here is a way of doing it in PHP with parallel cURL. This script scrapes all the extensions present in the Chrome webstore (ranked by popularity) and retrieves information such as:
Number of users
Number of star-ratings
Number of text reviews
Number of characters for each text-review (max 100 reviews scraped for each extension)
//GET URL
$url0 = "https://chrome.google.com/";
//AUTO LOOP
foreach(range(0, 705, 5) as $x) {
//Nb PAGES TO DOWNLOAD
$frompge = $x+1;
$topge = $x+5;
$nbpages = ($topge - $frompge)+1;
$zitems = $nbpages*20;
//MULTI cURL INIT
$mh = curl_multi_init();
$running = null;
//GENERATE URLs ARRAY
$urls = array();
for ($a = $frompge; $a <= $topge; $a++){
$aa = $url0 . 'webstore/list/most_popular/'. $a .'?category=ext';
$urls[] = $aa;
}
foreach ($urls as $name => $url)
{
$c[$name]=curl_init($url);
curl_setopt($c[$name], CURLOPT_HEADER, false);
curl_setopt($c[$name], CURLOPT_FAILONERROR, true);
curl_setopt($c[$name], CURLOPT_FOLLOWLOCATION, true);
curl_setopt($c[$name], CURLOPT_AUTOREFERER, true);
curl_setopt($c[$name], CURLOPT_RETURNTRANSFER, true);
curl_setopt($c[$name], CURLOPT_TIMEOUT, 10);
curl_multi_add_handle ($mh,$c[$name]);
}
// execute all queries simultaneously, and continue when all are complete
do {
curl_multi_exec($mh, $running);
} while ($running >0);
$html = array();
foreach ($urls as $name => $url)
{
$html[]=curl_multi_getcontent($c[$name]);
curl_multi_remove_handle($mh,$c[$name]);
curl_close($c[$name]);
}
curl_multi_close($mh);
for ($b = 0; $b <= $nbpages-1; $b++) {
// Parse the HTML information and return the results.
$dom = new DOMDocument();
#$dom->loadHtml($html[$b]);
$xpath = new DOMXPath($dom);
$links = $xpath->query("//a[contains(#class, 'title-a')]");
$result = array();
foreach ( $links as $item ) {
$newDom = new DOMDocument;
$newDom->appendChild($newDom->importNode($item,true));
$xpath = new DOMXPath( $newDom );
$cleaner = array(" users", " user", "(", ")", ","," ");
$data = str_replace($cleaner,"",trim($xpath->query("//script")->item(0)->nodeValue));
list($b1,$id,$b2,$b3,$b4,$name,$b5,$b6,$b7,$b8,$b9,$b10,$b11,$b12,$b13,$nbusers) = explode("\"", $data);
$label = str_replace(" ", "", strtolower(ereg_replace("[^A-Za-z0-9 ]", "", $name)));
//CATEGORIES (based on nb of users)
if($nbusers<100){$category = '1';$color = 'inherit';}
else if($nbusers>=100 && $nbusers<1000){$category = '2';$color = '#E6EEEE';}
else if($nbusers>=1000 && $nbusers<10000){$category = '3';$color = '#CDDEDE';}
else if($nbusers>=10000 && $nbusers<100000){$category = '4';$color = '#B5CDCD';}
else if($nbusers>=100000 && $nbusers<1000000){$category = '5';$color = '#9CBDBD';}
else if($nbusers == '1000000+'){$category = '6';$color = '#83ACAC';}
else{$category = '-9';}
/////////////////////////////////////////////LOOP REVIEWS
$extURL = 'http://chrome.google.com/extensions/permalink?id='.$id;
$c1 = curl_init('https://chrome.google.com/reviews/json/search');
$c1a = curl_init('https://chrome.google.com/reviews/json/search');
$c2 = curl_init('https://chrome.google.com/reviews/json/lookup');
$fields1 = http_build_query(array(
'req' => '{"searchSpecs":[{"requireComment":true,"entities":[{"url":"'.$extURL.'"}],"groups":["public_comment"],"matchExtraGroups":true,"sortBy":"quality","startIndex":0,"numResults":100,"includeNickNames":false}],"applicationId":94}',
));
$options1 = array(
CURLOPT_RETURNTRANSFER => true,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_POST => true,
CURLOPT_TIMEOUT => 10,
CURLOPT_POSTFIELDS => $fields1,
);
$fields1a = http_build_query(array(
'req' => '{"searchSpecs":[{"requireComment":true,"entities":[{"url":"'.$extURL.'"}],"groups":["public_comment"],"matchExtraGroups":true,"startIndex":0,"numResults":100,"includeNickNames":false}],"applicationId":94}',
));
$options1a = array(
CURLOPT_RETURNTRANSFER => true,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_POST => true,
CURLOPT_TIMEOUT => 10,
CURLOPT_POSTFIELDS => $fields1a,
);
$fields2 = http_build_query(array(
'req' => '{"entities":[{"url" : "'.$extURL.'", "includeAggregateInfo" : true}],"applicationId":94}',
));
$options2 = array(
CURLOPT_RETURNTRANSFER => true,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_POST => true,
CURLOPT_TIMEOUT => 10,
CURLOPT_POSTFIELDS => $fields2,
);
curl_setopt_array($c1, $options1);
curl_setopt_array($c1a, $options1a);
curl_setopt_array($c2, $options2);
$mh2 = curl_multi_init();
curl_multi_add_handle($mh2,$c1);
curl_multi_add_handle($mh2,$c1a);
curl_multi_add_handle($mh2,$c2);
$active = null;
do {
curl_multi_exec($mh2, $active);
} while ($active >0);
//close the handles$c1 = curl_init('https://chrome.google.com/reviews/json/search');
$json1=curl_multi_getcontent($c1);
$json1a=curl_multi_getcontent($c1a);
$json2=curl_multi_getcontent($c2);
curl_multi_remove_handle($mh2, $c1);
curl_multi_remove_handle($mh2, $c1a);
curl_multi_remove_handle($mh2, $c2);
curl_multi_close($mh2);
$data1 = json_decode(utf8_encode($json1), true);
$data1a = json_decode(utf8_encode($json1a), true);
$data2 = json_decode(utf8_encode($json2), true);
if ($data1['channelHeader']['errorCode']) return;
$nbreviews = $data1['searchResults'][0]['numAnnotations'];
if ($nbreviews > 100){$nbreviews2=100;}
else{$nbreviews2=$nbreviews;}
//Sum strings
$comments = $data1['searchResults'][0]['annotations'];
$sum =0;
foreach($comments as $comment){
$msg = preg_replace('/[\n\r\t]/', ' ', htmlspecialchars($comment['comment']));
$msg = str_replace(">", "", $msg);
$msg = str_replace(" ", "", $msg);
$strlen = strlen($msg);
$sum += $strlen;
}
$add = $sum;
$final = $add/$nbreviews2;
//Sum strings A
if ($data1a['channelHeader']['errorCode']) return;
$nbreviewsa = $data1a['searchResults'][0]['numAnnotations'];
$commentsa = $data1a['searchResults'][0]['annotations'];
$suma =0;
foreach($commentsa as $commenta){
$msga = preg_replace('/[\n\r\t]/', ' ', htmlspecialchars($commenta['comment']));
$msga = str_replace(">", "", $msga);
$msga = str_replace(" ", "", $msga);
$strlena = strlen($msga);
$suma += $strlena;
}
$adda = $suma;
$finala = $adda/$nbreviews2;
//Ratings
if ($data2['channelHeader']['errorCode']) return;
$nbratings = $data2['annotations'][0]['aggregateInfo']['numRatings'];
$nbstars = $data2['annotations'][0]['aggregateInfo']['averageRating'];
$delta = $nbratings - $nbreviews;
$ratio = $nbratings/$nbusers;
$ratio2 = $nbreviews/$nbusers;
////////////////////////////////////////////END LOOP REVIEWS
//PUT VALUES TOGETHER
$result[] = array($name,$label,$id,$category,$nbusers,$nbratings,$nbreviews,$nbreviewsa,$delta,$ratio,$ratio2,$nbstars,$nbreviews2,$add,$final,$adda,$finala);
}//END FOREACH
//print_r($result,false);
//DISPLAY RESULTS
for ($z = 0; $z <= 20; $z++) {
echo "<tr><td class=\"non\">" .$result[$z][0] . "</td><td class=\"non\">" .$result[$z][1] . "</td><td>" .$result[$z][3] . "</td><td>" .$result[$z][4] . "</td><td>" .$result[$z][5] . "</td><td>" .$result[$z][6] . "</td><td>" .$result[$z][7] . "</td><td>" .$result[$z][8] . "</td><td>" .$result[$z][9] . "</td><td>" .$result[$z][10] . "</td><td>" .$result[$z][11] . "</td><td>" .$result[$z][12] . "</td><td>" .$result[$z][13] . "</td><td>" .$result[$z][14] . "</td><td>" .$result[$z][15] . "</td><td>" .$result[$z][16] . "</td></tr>";
ob_flush();
flush();
}
}
}//END FOREACH

Resources