get array out of loop - php

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;
}
}

Related

Understanding coderbyte back-end challenge

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);

How to call this curl API request to get the highest 'likelihood' json field name?

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";

php how to calculate numbers sum after the loop

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)

PHP Foreach loop only displaying last result

I am having a bit of trouble with some code where in an array I have a list of 2 and the function is only displaying the last in the list.
Here is the code:
<?php
function getKeywordPosition($theurl,$thekeywords) {
$theurl = $theurl;
$thekeywords = $thekeywords;
$found = false;
$x = 0;
for($x; $x < 64 && $found == false;)
{
$url = "http://ajax.googleapis.com/ajax/services/search/web?v=1.0&"
. "q=".stripslashes(str_replace(' ', '%20', $thekeywords)).'&start='.$x;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_REFERER, 'http://www.boo.com');
$body = curl_exec($ch);
curl_close($ch);
$json = json_decode($body);
$x4 = $x + 4;
$old_x = $x;
for($x; $x < $x4 && $found == false; $x = $x + 1)
{
if (strpos($json->responseData->results[$x-$old_x]->unescapedUrl, strtolower($theurl)) !== false)
{
$found = true;
}
}
// now have some fun with the results...
}
if($found)
{
echo '<strong>'.$theurl.'</strong> is located as the <strong>'.$x.'</strong> result when searching for <strong>'.stripslashes($thekeywords).'</strong>';
echo '<br>';
}
}
$list = array('php.com'=>'php', 'php.com'=>'php');
foreach($list as $key => $value){
getKeywordPosition($key,$value);
}
?>
Why is this not working properly?
Unless this is a badly contrived example, then th issue is you have duplicate keys in your array:
$list = array('php.com'=>'php', 'php.com'=>'php');
This array has a single entry
You coud refactor like so:
$list = array(
array('url'=>'php.net', 'keyword'=>'php'),
array('url'=>'php.net', 'keyword'=>'arrays'),
array('url'=>'php.net', 'keyword'=>'anotherkeyword')
);
foreach($list as $entry){
getKeywordPosition($entry['url'], $entry['keyword']);
}

Crawling images from a website

I am trying to crawl images from a website using PHP.
The page that I am trying to crawl is:
http://www.reebonz.com.sg/event/t7349#/event/t7349
But using my code I only get the href of my header. My code is:
<?php
require_once ('function.php');
$advt_id = "88477";
$programurl = "http://www.reebonz.com.sg/event_list/1/";
$baseurl = "http://www.reebonz.com.sg/event_list/1/";
$crawl_data []= array ( "department" => 0, "category" => "bags" , "advt_cat" => "BALENCIAGA", "cat_url" => 'http://www.reebonz.com.sg/event/t7349#/event/t7349');
$data = get_data($url);
$product_raw = splice_data ($data, 'ul class="rec-items-ul ng-scope"',1, '</ul>',1);
$product_list = splice_list ($product_raw, 'href="', '"');
echo "\n**** Got Product List ".count($product_list)." ***\n";
print_r ($product_list);
foreach ($product_list as $product)
{
if ((strlen($product) < 10))
{
echo $product;
continue;
}
$url = $baseurl.$product;
$data = get_data($url);
$img_data = splice_data ($data, 'class="rbz_product-zoom-image row"', 1, '</div>', 1);
$img_url = splice_data ($img_data, 'href="',1, '"', 1);
echo $img_url;
$filePath = $crawl_cat['category']."\\".$crawl_cat['advt_cat'];
if (!file_exists($filePath)) {
mkdir($filePath, 0777, true);
}
grab_image($img_url,$filePath);
//grab_image($img_url5,$filePath);
echo "*";
}// end of product insert for
?>
the function.php is:
function splice_data ($data, $startstr, $startoccur, $endstr, $endoccur)
{
if ($startoccur > 1)
{
for ($i = 1, $startpos = 1 ; $startoccur >= $i; $i++, $startpos++)
{
$startpos = stripos($data,$startstr,$startpos);
//echo $startpos. "\n";
}
$start = $startpos;
}
else
$start = stripos($data,$startstr,$startoccur);
$start_index = strlen($startstr);
$end = stripos($data,$endstr,$start + $start_index ) ;
$splice_data = substr($data,$start + $start_index, $end - ($start + $start_index) );
return $splice_data;
}
function splice_list ($img_data, $start_str, $end_str, $find = '', $replace = '')
{
for ($i = 1, $j = 1; stripos($img_data,$start_str,$i) > 1 ;)
{
$start = stripos($img_data,$start_str,$i);
$start_len = strlen($start_str);
$end = stripos($img_data,$end_str,$start + $start_len) ;
$data_list[] = str_replace($find,$replace,substr($img_data, $start + $start_len , $end - $start - $start_len)) ;
$i = $end;
$j++;
}
$result = array_unique($data_list);
return $result;
}
function get_data($url, $ckfile="", $cookie="")
{
$toCheckURL = $url;
// This all sets up the CURL actions to check the page
$header=array(
// 'User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.2.12) Gecko/20101026 Firefox/3.6.12',
'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'Accept-Language: en-us,en;q=0.5',
'Accept-Encoding: gzip,deflate',
'Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7',
'Keep-Alive: 115',
'Connection: keep-alive',
);
$proxies = array();
$ch = curl_init();
if (isset($proxy)) { // If the $proxy variable is set, then
curl_setopt($ch, CURLOPT_PROXY, $proxy); // Set CURLOPT_PROXY with proxy in $proxy variable
}
curl_setopt($ch, CURLOPT_URL, $toCheckURL);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_NOBODY, false);
if (isset($ckfile) && $ckfile !="" and !empty($ckfile))
{
curl_setopt ($ch, CURLOPT_COOKIEFILE, $ckfile);
}
curl_setopt($ch,CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT,60);
curl_setopt($ch, CURLOPT_TIMEOUT,90);
curl_setopt($ch, CURLOPT_MAXREDIRS, 10); //follow up to 10 redirections - avoids loops
if($cookie != "")
curl_setopt($ch,CURLOPT_HTTPHEADER, array($cookie));
curl_setopt($ch,CURLOPT_USERAGENT,$agents[array_rand($agents)]);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
The output that I get now is:
**** Got Product List 8 *** Array ( [0] => //netdna.bootstrapcdn.com/twitter-
bootstrap/2.3.2/css/bootstrap-combined.no-icons.min.css [1] => //netdna.bootstrapcdn.com/font-
awesome/3.2.1/css/font-awesome.css [2] =>
http://www.reebonz.com.sg/sites/all/themes/custom/octopus2/xfavicon.ico.pagespeed.ic.jT8Y7LgYBc.png
[3] => http://www.octopus2.local/sites/all/themes/custom/octopus2/css/reebonz-ie.css [4] =>
http://www.reebonz.com.sg/sites/all/modules,_contrib,_jquery_update,_replace,_ui,_themes,_base,_minified,_jquery.ui.core.min.css,qn1a78z+modules,_contrib,_jquery_update,_replace,_ui,_themes,_base,_minified,_jquery.ui.theme.min.css,qn1a78z+modules,_contrib,_jquery_update,_replace,_ui,_themes,_base,_minified,_jquery.ui.slider.min.css,qn1a78z+modules,_contrib,_panels,_css,_panels.css,qn1a78z+modules,_custom,_mailcheck,_css,_mailcheck.css,qn1a78z+themes,_custom,_octopus2,_css,_bootstrap.css,qn1a78z+themes,_custom,_octopus2,_css,_reebonz-core.css,qn1a78z+themes,_custom,_octopus2,_css,_reebonz-social-network.css,qn1a78z+themes,_custom,_octopus2,_css,_reebonz-....
What is wrong with my code?Is there any simple way to do this??
use php DomDocument:
$doc = new DOMDocument();
$doc->loadHTML(your_html_code);
$images = $doc->getElementsByTagName('img');
foreach ($images as $img) {
//do whatever you like
}
Download this library : http://sourceforge.net/projects/simplehtmldom/
And the below code will work
(include that library in top)
<?php
error_reporting(1);
include_once('simple_html_dom.php');
$html = new simple_html_dom();
$html->load_file('https://www.google.co.in/search?q=shahrukh+khan&newwindow=1&biw=1375&bih=791&source=lnms&tbm=isch&sa=X&sqi=2&ved=0ahUKEwi1rO6AjZrKAhWSBY4KHWSGBDQQ_AUIBygC');
$reviews = $html->find('img');
$fetched_images = '';
foreach($reviews as $link)
{
//find review ID if not null
if($link->{'src'} != ''){
$review_ID = $link->{'src'};
$fetched_images[] = $review_ID;
}
}
?>
<ul>
<?php foreach ($fetched_images as $fetched_image): ?>
<li style="display:inline-block"><img src="<?php echo $fetched_image;?>"></li>
<?php endforeach ?>
</ul>
<?php
include_once('simple_html_dom.php');
$target_url = "Your URL here";
$html = new simple_html_dom();
$html->load_file($target_url);
$images = $html->find('img');
/**foreach($images as $link){
//find review ID if not null
if($link->{'src'} != ''){
$image_ID = $link->{'src'};
$fetched_images[] = $image_ID;
}
}*/
foreach ($images as $fetched_image){
echo $fetched_image;
}
?>

Categories