I've been working on a movie review website and I can't quite get the calculate average rating functionality working. In the code below, In the first instance I am grabbing the current rating of the movie [$totalRating] via an API and setting the counter [$numRatings]. Then via an API I am collecting all of the ratings of that movie, attempting to to add them to the total rating, updating the counter within the loop.
However, when I rate movies they simply are updated to the registered rating (say I input an 8 it becomes an 8) and the division never takes place. Was wondering if anyone has any solutions or can see where I am going wrong?
function setUserRating($movieID)
{
$ep = "http://localhost:8888/MovieRating/api/?movieDetails=$movieID";
$response = file_get_contents($ep);
$Movies = json_decode($response, true);
$baseRating = $Movies[0]['movieRating'];
$numRatings = 1;
$totalRating = $baseRating;
$ep = "http://localhost:8888/MovieRating/api/?allMovieRatings=$movieID";
$resp = file_get_contents($ep);
$userRatings = json_decode($resp, true);
if (isset($userRatings['movie_ratings'])) {
$reviews = $userRatings['movie_ratings'];
}
if (isset($reviews)) {
foreach ($reviews as $row) {
$numRatings++;
$totalRating = $totalRating + $row['rating'];
}
}
$avgUserRating = $totalRating / $numRatings;
return $avgUserRating;
}
Might just need a small adjustment
function setUserRating($movieID)
{
$ep = "http://localhost:8888/MovieRating/api/?movieDetails=$movieID";
$response = file_get_contents($ep);
$Movies = json_decode($response, true);
$baseRating = $Movies[0]['movieRating'];
$numRatings = 0; //1
$totalRating = 0; //$baseRating;
$ep = "http://localhost:8888/MovieRating/api/?allMovieRatings=$movieID";
$resp = file_get_contents($ep);
$userRatings = json_decode($resp, true);
if (array_key_exists($userRatings['movie_ratings'])) {
$reviews = $userRatings['movie_ratings'];
}
if (isset($reviews)) {
foreach ($reviews as $row) {
++$numRatings;
$totalRating += $row['rating'];
}
}
return $numRatings > 0 ? $totalRating / $numRatings : $baseRating;
}
Related
I have a google task which gets all companies from my firebase database. I then go through each of those companies in a loop and call additional task for updating each specific company. My problem is that my companies count is increasing and when doing foreach like this i can get into memory limit issues. Here is the actual code for calling the tasks and subtasks:
$router->get('companies', function () use ($router) {
$slackDataHelpersService = new \App\Services\SlackDataHelpersService();
$companiesDocuments = $slackDataHelpersService->getCompanies();
foreach ($companiesDocuments->documents() as $document) {
$cid = $document->id();
createTask('companies', 'updateCompany', "{$cid}");
}
return res(200, 'Task done');
});
How can i separate my initial companies documents into chunks and call a task for each of those chunks? For example, a task that will go through every 100 documents instead of the whole list?
Here is what i tried without success(i used members in this case):
$router->get('test2', function () use ($router) {
$db = app('firebase.firestore')->database();
$membersRef = $db->collection('companies')->document('slack-T01L7H2NDPB')->collection('members');
$query = $membersRef->orderBy('created', 'desc')->limit(10);
$perPage = 10;
$batchCount = 10;
$lastCreated = null;
while ($batchCount == $perPage) {
$loopQuery = clone $query;
if ($lastCreated != null) {
$loopQuery->startAfter($lastCreated);
}
$docs = $loopQuery->documents();
$docsRows = $docs->rows();
$batchCount = count($docsRows);
if ($batchCount > 1) {
$lastCreated = $docsRows[$batchCount - 1];
}
echo $lastCreated['created'];
//createTasksByDocs($docs);
}
//return res(200, 'Task done');
});
I ended up making a function which uses a while loop and loops until it reaches the limit:
function paginateCollections($ref, $limit, $functionName)
{
$query = $ref->orderBy('created', 'desc')->limit($limit);
$perPage = $limit;
$batchCount = $limit;
$lastCreated = null;
while ($batchCount == $perPage) {
$loopQuery = clone $query;
if ($lastCreated != null) {
$loopQuery = $loopQuery->startAfter([$lastCreated]);
}
$docs = $loopQuery->documents();
$docsRows = $docs->rows();
$batchCount = count($docsRows);
if ($batchCount > 1) {
$lastCreated = $docsRows[$batchCount - 1]['created'];
}
if (function_exists($functionName)) {
$functionName($docs);
}
}
}
I am currently running a wordpress backend and want to display some tweets based on hastags on my website. For the general API request and database storage, I use this function:
private function parseRequest($json) {
$tmp = $json;
$result = array();
if (isset($json['statuses'])) {
$tmp = $json['statuses'];
}
if (isset($tmp) && is_array($tmp)){
foreach ($tmp as $t) {
$this->image = null;
$this->media = null;
$tc = new \stdClass();
$tc->feed_id = $this->id();
$tc->id = $t['id_str'];
$tc->type = $this->getType();
$tc->nickname = '#'.$t['user']['screen_name'];
$tc->screenname = (string)$t['user']['name'];
$tc->userpic = str_replace('.jpg', '_200x200.jpg', str_replace('_normal', '', (string)$t['user']['profile_image_url']));
$tc->system_timestamp = strtotime($t['created_at']);
$tc->text = $this->getText($t);
$tc->userlink = 'https://twitter.com/'.$t['user']['screen_name'];
$tc->permalink = $tc->userlink . '/status/' . $tc->id;
$tc->media = $this->getMedia($t);
#$tc->additional = array('shares' => (string)$t['retweet_count'], 'likes' => (string)$t['favorite_count'], 'comments' => (string)$t['reply_count']);
if ($this->isSuitablePost($tc)) $result[$tc->id] = $tc;
}
}
return $result;
}
Now I am looking for a function that counts all the variable in the "additional array together e.g. shares + likes + comments and sorts all posts based on the resulting number.
I am using the standard wordpress sql database. I cannot find a solution or I am just blind.
Thanks in regards
You could use a simple usort function:
usort($tc, function($a, $b) {
$a_sum = array_sum($a->additional);
$b_sum = array_sum($b->additional);
if ($a_sum == $b_sum) {
return 0;
}
return ($a_sum < $b_sum) ? -1 : 1;
});
I am using the following PHP code to fetch some data from my database. It contains chats and messages between users in those chats. I want to return the information of both users plus the messages they exchanged. My test data has two chats with ID's 1 and 2. There are two messages, both in chat 1, however for some reason they are returned for both chats 1 and 2. I'm not sure what the problem in my code is.
$response = array();
$myArray = array();
while($row = $user_chats->fetch_array())
{
$myArray["chatId"] = $row["chat_id"];
$myArray["user1_id"] = $row["user1"];
$myArray["user2_id"] = $row["user2"];
$myArray["user1_name"] = $user1_name;
$myArray["user2_name"] = $user2_name;
$myArray["user1_profile_pic"] = $result_user1["profile_pic"];
$myArray["user2_profile_pic"] = $result_user2["profile_pic"];
$messages = array();
$chat_idd = $row["chat_id"];
$chat_messages = mysqli_query($conn,"SELECT * FROM messages WHERE chatID = '$chat_idd' ORDER BY timestamp ASC");
$count = 1;
while($roww = $chat_messages->fetch_array()) {
if ($row["chat_id"] == $roww["chatID"]) {
$messages["message_id"] = $roww["message_id"];
$messages["sender"] = $roww["sender"];
$messages["chatId"] = $roww["chatID"];
$messages["text"] = $roww["text"];
$messages["timestamp"] = $roww["timestamp"];
$myArray["message"][$count] = $messages;
$count = $count + 1;
}
else {
$myArray["message"]= 0;
}
}
$response[] = $myArray;
}
echo json_encode($response);
produces the following response:
[{"chatId":"1","user1_id":"32132132","user2_id":"2121","user1_name":"dwqd",
"user2_name":"dqdwdw","user1_profile_pic":"http:\/\/graph.facebook.com\/dwqwqdqdwdw\/picture?type=large","user2_profile_pic":"WDQdwqwqddqwdqwdq","message":{"1":{"message_id":"24242241","sender":"32132132","chatId":"1","text":"hello i am",
"timestamp":"2016-05-24 17:13:08"},"2":{"message_id":"421421","sender":"32132132",
"chatId":"1","text":"great","timestamp":"2016-05-24 17:15:08"}}},{"chatId":"2","user1_id":"23413524635","user2_id":"32132132","user1_name":false,
"user2_name":"dwqd","user1_profile_pic":
WDQdwqwqddqwdqwdq" ,"user2_profile_pic":"http:\/\/graph.facebook.com\/32132132\/picture?type=large",
"message":{"1":{"message_id":"24242241","sender":"32132132","chatId":"1","text":"hello i am",
"timestamp":"2016-05-24 17:13:08"},"2":{"message_id":"421421","sender":"32132132","chatId":"1",
"text":"great","timestamp":"2016-05-24 17:15:08"}}}]
You need to initialize $myArray at each iteration through the loop, e.g.
while($row = $user_chats->fetch_array()) {
$myArray = array();
I am struggling to understand how to make use of the paging mechanism with batch requests to Facebook's Graph API.
My issue with the code below is that despite attempting to track an offset for each facebook_id that is in my database, I'm unable to determine when a particular request has come up empty and therefore shouldn't be requested again.
I'm parsing the facebook_id's from the paging array in the responses. At the point when no more posts are available, FB returns an empty data array and therefore I'm unable to recognize which request has no more pages, and thus reduce the subsequent requests. Each time I'm querying FB with $fb_batch_limit urls despite the fact not all requests have returned a paging token from the previous call.
How would a real programmer tackle this problem?
$posts = array();
//$fb_batch_limit = 30;
$fb_batch_limit = 2;
$fb_req_limit=10;
$facebook = new Facebook(array(
'appId' => $fb_app_id,
'secret' => $fb_app_secret
));
$facebook->setAccessToken($fb_user_token);
$index = 0;
$since = '1Jan14';
$until = 'today';
$num_records_res = $oDB->select("SELECT count(*) as count FROM facebook f");
$num_records_row = mysqli_fetch_array($num_records_res);
$num_records = $num_records_row['count'];
while($index < $num_records) {
printf("# %d to %d\n", $index, $index+$fb_batch_limit);
$res = $oDB->select("SELECT facebook_id FROM facebook f ".
"LIMIT $index, $fb_batch_limit");
$index = $index + $fb_batch_limit;
$offsets = array();
while($rr = mysqli_fetch_array($res)){
$offsets[$rr['facebook_id']] = 0;
}
if (!count($offsets)) {
printf("no more accounts\n");
break;
}
$r=1;
do {
$urls = array();
foreach ($offsets as $fbid => $offset) {
$tmp["method"] = 'GET';
$tmp["relative_url"] = "/".$fbid."/feed?fields=likes.limit(1).summary(true)&offset=$offset&limit=$fb_req_limit";//&since=$since&until=$until";
$tmp["include_headers"] = false;
$urls[] = $tmp;
}
$numurls = count($urls);
printf("$r: fetching %d urls have %d posts\n", $numurls, count($posts));
$response = $facebook->batch($urls);
foreach ($response as $result) {
if (array_key_exists("error", $result)) {
//FIXME handle rate limits somehow
print_r($result);
die;
}
if (array_key_exists("paging", $result)) {
$fbid = substr(parse_url($result['paging']['previous'])['path'],6);
$fbid = substr($fbid, 0, -5);
if (($count = count($result['data'])) > 0) {
$posts = array_merge($posts, $result['data']);
if (array_key_exists("paging", $result) && array_key_exists("next", $result["paging"])) {
if (array_key_exists($fbid, $offsets)) {
$offsets[$fbid] += $count;
}
}
}
else {
printf("$fbid complete with ".
$offsets[$fbid]." posts\n");
unset($offsets[$fbid]);
}
}
else {
// how to stop requesting this single url?
print_r($result);
echo "--\n";
$numurls--;
}
}
} while (++$r && $numurls);
}
I have an array containing several variables from my sql database.
{"gold":"0","silver":"0","bronze":"0","gdp":"12959563902","population":"3205000","country_name":"Albania"}, {"gold":"1","silver":"0","bronze":"0","gdp":"188681000000","population":"35468000","country_name":"Algeria"}
I have an additional variable called $score that uses information from the database to calculate this score. I want to know how I can loop through and add the correct score to each country in the array.
My Original Code:
$row = $res->fetchRow();
$resGold = $row['gold'];
$resSilver = $row['silver'];
$resBronze = $row['bronze'];
$resGdp = $row['gdp'];
$resPopulation = $row['population'];
$resCountry = $row['country_name'];
$gold_score = ($resGold * $gold_value);
$silver_score = ($resSilver * $silver_value);
$bronze_score = ($resBronze * $bronze_value);
if($population == true){
$score = (($gold_score + $silver_score + $bronze_score)/$resPopulation);
}
else if($gdp == true){
$score = (($gold_score + $silver_score + $bronze_score)/$resGdp);
}
$result = $res->fetchAll();
$result[] = array('score' => $score);
echo json_encode($result);
Your code will be something like this:
$json_data = '{"gold":"0","silver":"0","bronze":"0","gdp":"12959563902","population":"3205000","country_name":"Albania"},
{"gold":"1","silver":"0","bronze":"0","gdp":"188681000000","population":"35468000","country_name":"Algeria"}';
$countries_info_new = array();
$countries_info = json_decode($json_data);
foreach($countries_info as $country_info){
$country_info['score'] = Get_country_score($country_info['country_name']);
$countries_info_new[]=$country_info;
}
$new_json_data = json_encode($countries_info_new);