I have following loop to calculate comments and likes
function AddCampaignDetails($next=null){
$AccessToken = ACCESS_TOKEN;
$url = "https://api.instagram.com/v1/tags/canonfanatic/media/recent?access_token=".$AccessToken;
if($url !== null) {
$url .= '&max_tag_id=' . $next;
}
/*//Also Perhaps you should cache the results as the instagram API is slow
$cache = './'.sha1($url).'.json';
if(file_exists($cache) && filemtime($cache) > time() - 60*60){
// If a cache file exists, and it is newer than 1 hour, use it
$jsonData = json_decode(file_get_contents($cache));
}else{
$jsonData = json_decode((file_get_contents($url)));
file_put_contents($cache,json_encode($jsonData));
}*/
$Ch = curl_init();
curl_setopt($Ch, CURLOPT_URL, $url);
curl_setopt($Ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($Ch, CURLOPT_TIMEOUT, 20);
$Result = curl_exec($Ch);
curl_close($Ch);
$Result = json_decode($Result);
$Data = $Result->data;
//echo "<pre>"; print_r($Data); echo "</pre>";
$CommentsSum = 0;
$LikesSum = 0;
for($i=0; $i<count($Data); $i++){
$CommentsSum += $Data[$i]->comments->count;
$LikesSum += $Data[$i]->likes->count;
}
//echo ' Comments '.$CommentsSum;
//echo ' Likes '.$LikesSum;
echo "<br />";
if(isset($Result->pagination->next_url) && !empty($Result->pagination->next_url)){
$next = $Result->pagination->next_url;
$this->AddCampaignDetails($next);
}else{
$NextUrl = "";
die;
}
return $result;
}
After this loop, I have echo $CommentsSum; variable and get this output
183
306
320
42
Now I want above number sum 851.
Any idea?
Thanks.
Your $Data[$i]->comments->count must be a number, and it's seem that is a string, so it's merging string instead of doing math.
And If you really have a new line between each number (like you said in echo) maybe $Data[$i]->comments->count is equal to "183\n"
use for example :
$CommentsSum += intval($Data[$i]->comments->count)
Related
This is the challenge: In the PHP file, write a program to perform a GET request on the route https://coderbyte.com/api/challenges/json/age-counting which contains a data key and the value is a string which contains items in the format: key=STRING, age=INTEGER. Your goal is to count how many items exist that have an age equal to or greater than 50, and print this final value.
Example Input
{"data":"key=IAfpK, age=58, key=WNVdi, age=64, key=jp9zt, age=47"}
Once your function is working, take the final output string and replace all characters that appear in your ChallengeToken with --[CHAR]--.
Your ChallengeToken: ndv946kie1
Here's my code:
<?PHP
$ch = curl_init('https://coderbyte.com/api/challenges/json/age-counting');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, 0);
$data = curl_exec($ch);
curl_close($ch);
//print_r(json_decode($data, true));
$arr = json_decode($data, true);
$items = explode(', ', $arr['data']);
$count = 0;
foreach ($items as $item){
//print_r($item . PHP_EOL);
if(str_starts_with($item,'age=')===true){
$age = explode('=',$item)[1];
if($age >= 50)
$count++;
}
}
$str = 'ndv946kie1';
$chars = str_split($str);
$final = '';
foreach ($chars as $char){
$final = $final . $count;
}
print_r($final);
?>
coderbyte says incorrect output, maybe I misunderstood the last instruction?
I had the same problem...
Giving below the code that worked for me:
<?php
$ch = curl_init('https://coderbyte.com/api/challenges/json/age-counting');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, 0);
$data = curl_exec($ch);
curl_close($ch);
//print_r(json_decode($data, true));
$arr = json_decode($data, true);
$items = explode(', ', $arr['data']);
$count = 0;
foreach ($items as $item){
//print_r($item . PHP_EOL);
if(str_starts_with($item,'age=')===true){
$age = explode('=',$item)[1];
if($age >= 50)
$count++;
}
}
print_r($count);
?>
Please try with this
<?php
$ch = curl_init('https://coderbyte.com/api/challenges/json/age-counting');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, 0);
$data = curl_exec($ch);
curl_close($ch);
$json_data = json_decode($data, true);
$items = explode(', ', $json_data['data']);
$count = array_reduce($items, function ($count, $item) {
if (strpos($item, 'age=') !== false) {
$age = explode('=', $item)[1];
if ($age >= 50) return $count + 1;
}
return $count;
}, 0);
print_r($count);
I need get array out of loop (I need used array, and not, last value)
loop
for ($x = 1; $x < $numero; $x++) {
$frase = $frase_script[$x];
$distrito1 = (explode(',',$frase));
echo $distrito1[0]}
Variable out
$ultimo_nome = $distrito1[0];
I need used array, and not, last value
echo "<br> I need print array, and not, last value".$ultimo_nome;
error: prints the last value and not an array.
Example
all code
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://api.geonames.org/searchJSON?username=country=pt&lang=pt&q=lisbon&fcode=ADM2&adminCode1=14&style=SHORT&maxRows=1000");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, FALSE);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
"Accept: application/json"
));
$response = curl_exec($ch);
curl_close($ch);
$frase_script = (explode(',',$response));
$frase = $frase_script[0];
$palavra = (explode(':',$frase));
$numero = $palavra[1];
$frase_script = (explode('"name":',$response));
echo '[';
for ($x = 1; $x < $numero; $x++) {
$frase = $frase_script[$x];
$distrito1 = (explode(',',$frase));
echo $distrito1[0]; }
$ultimo_nome = $distrito1[0];
echo $ultimo_nome;
echo ']';
echo "<br> I need print array, and not, last value".$ultimo_nome;
if you need print all the elements but not the lasy you could use
$distrito1 = (explode(',',$frase));
$numElem = count($distrito1);
foreach ($distrito1 as $key => $value){
if ( $key < $numElem-1 ){
echo $value;
} else {
break;
}
}
i am finishing a project, but i need to compare if a HTTP Status Code is the same as another. I have a big algorithm and i reduced them and i identified the problem:
I have an array called "$file_headers", and in the ["Status"] position saves "HTTP/1.1 301 Moved Permanently", and in the if clause i compare to "HTTP/1.1 301 Moved Permanently" (which obviously is the same), but my code doesn't say the same as me. I detect the HTTP Status Code using cURL. My PHP code is the following:
<?php
// create curl resource
$ch = curl_init();
// set url
curl_setopt($ch, CURLOPT_URL, "fb.com");
//return the transfer as a string
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
//enable headers
curl_setopt($ch, CURLOPT_HEADER, 1);
//get only headers
curl_setopt($ch, CURLOPT_NOBODY, 1);
// $output contains the output string
$output = curl_exec($ch);
// close curl resource to free up system resources
curl_close($ch);
$data = explode("\n",$output);
$headers_one = $data;
$headers_two = array();
$headers_two['Status'] = $data[0];
array_shift($data);
foreach($data as $part){
$middle = explode(":",$part);
$msg = null;
if(sizeof($middle) > 2){
if(strpos($middle[0],"Location") === false){
for($i = 1; $i <= sizeof($middle)-1;$i++){
$msg .= $middle[$i];
}
} else {
for($i = 1; $i <= sizeof($middle)-1;$i++){
if($i == 1){
$msg .= $middle[$i] . ":";
} else {
$msg .= $middle[$i];
}
}
}
} else if(isset($middle[1])){
$msg = $middle[1];
}
$headers_two[trim($middle[0])] = trim($msg);
}
array_pop($headers_one);
array_pop($headers_one);
array_pop($headers_two);
$file_headers = $headers_two;
if($file_headers["Status"] === ("HTTP/1.1 301 Moved Permanently") || $file_headers["Status"] === ("HTTP/1.1 301")){
echo "OK!";
} else {
echo "NO!";
}
//print all headers as array
/*echo "<pre>";
print_r($headers_one);
echo "</pre><br />";*/
echo "<pre>";
echo $file_headers["Status"];
echo "</pre>";
?>
If anyone can help me i would appreciate it. THANKS AND HAVE A NICE DAY DEV!
$headers_two['Status'] is the only element you're not trim()ing, so it has some whitespace around it, which makes the comparison fail. Do it like this:
$headers_two['Status'] = trim($data[0]);
And it'll work just fine.
I'm trying to use this API from this site fullcontact for normalizing a number of possible names into 'likelihood values' for name extraction.
Tried the following code but it can't run Undefined offset: 2 error: $index_name = $possible_names[$n];. Moreover, I'm was stuck with the logic of extracting the name. Can someone help? Thanks
$possible_names = array("Jimmy Frank", "Wall Street"); // In this case Jimmy Frank should be the output person name
if (count($possible_names) > 1)
{
for ($n = 0; $n <= count($possible_names); $n++)
{
$index_name = $possible_names[$n];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://api.fullcontact.com/v2/name/normalizer.json?q=$index_name");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
$headers = array();
$headers[] = "X-Fullcontact-Apikey: APIKEY";
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$namenormalizer_result = curl_exec($ch);
if (curl_errno($ch)) {
echo 'Error:' . curl_error($ch);
}
else
{
$namejson_result = json_decode($namenormalizer_result, true);
$namejson_array[] = $namejson_result['likelihood'];
}
curl_close ($ch);
}
}
$possible_names is an array of size 2. Arrays are indexed from 0 so you need to remove the last index 2 which doesn't exist :
for ($n = 0; $n <= count($possible_names) - 1; $n++) {
}
or use strict condition :
for ($n = 0; $n < count($possible_names); $n++) {
}
For the extraction, you can use $namejson_result->nameDetails->fullName to extract fullName and $namejson_result->likelihood for likelihood :
$namejson_result = json_decode($result);
echo "likelihood for $index_name on " .
$namejson_result->nameDetails->fullName . " : " .
$namejson_result->likelihood . "\n";
I use the code in php to connect to the api and display the results...
<?php
ini_set('display_errors', 'On');
error_reporting(E_ALL);
require("OAuth.php");
$cc_key = "cc_key"; //cc_key
$cc_secret = "cc_secret"; // cc_secret key
$url = "https://yboss.yahooapis.com/ysearch/web";
$args = array();
$args["q"] = htmlspecialchars($_GET["q"]);
$args["format"] = "json";
$consumer = new OAuthConsumer($cc_key, $cc_secret);
$request = OAuthRequest::from_consumer_and_token($consumer, NULL,"GET", $url, $args);
$request->sign_request(new OAuthSignatureMethod_HMAC_SHA1(), $consumer, NULL);
$url = sprintf("%s?%s", $url, OAuthUtil::build_http_query($args));
//echo $url . "<br>"; test uri
$ch = curl_init();
$headers = array($request->to_header());
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$rsp = curl_exec($ch);
$results = json_decode($rsp, true);
//force to assoc-array, which will allow array-access
foreach($results['bossresponse']['web']['results'] as $result)
{
//$result is array here, but do the same stuff
echo '<a href="'.$result['url'].'" target=\'_blank\'>'.$result['title'].'</a></br>';
echo ''.$result['abstract'].'</br>';
echo '<a href="'.$result['url'].'" target=\'_blank\'>'.$result['dispurl'].'</a></br>';
}
?>
then write mini "pagination"
//$start = "&start=" . "0";
$start_val = $_GET['start'];
if ($start_val == "") $start_val = 0;
$start = "&start=" . $start_val;
// Some more code...
$count_val = 10;
$count = "&count=" . $count_val;
if ($query != "") {
if ($start_val != 0) {
echo 'previous';
echo '<span> | </span>';
}
echo 'next';
}
but "pagination" does not work =(
I can not understand why does not work
My question is how do I paginate results, since all the 50 results appear on the first web page only. I want to display ten results in every page.
Please HELP me
Thanks.