I am trying to create a small function to load data from different API endpoints into one array to work with / load data from. Right now my code is looking as follow;
$url1 = 'https://gameinfo.albiononline.com/api/gameinfo/guilds/uhmotNBAQ6-0vi9PFysRBg/members';
$url2 = 'https://gameinfo.albiononline.com/api/gameinfo/guilds/DWkD4B0uSsGQoryrz8Nuwg/members';
$url3 = 'https://gameinfo.albiononline.com/api/gameinfo/guilds/wSbCgimqTPy470n-wDQXPQ/members';
$url4 = 'https://gameinfo.albiononline.com/api/gameinfo/guilds/nmc0HQW-TZirTlnGzwbF-w/members';
$url5 = 'https://gameinfo.albiononline.com/api/gameinfo/guilds/WpV4yaVxSLW8QXH2Be40cA/members';
$api_endpoint1 = json_decode(file_get_contents($url1), true);
$api_endpoint2 = json_decode(file_get_contents($url2), true);
$api_endpoint3 = json_decode(file_get_contents($url3), true);
$api_endpoint4 = json_decode(file_get_contents($url4), true);
$api_endpoint5 = json_decode(file_get_contents($url5), true);
$merged_data = array();
foreach ($api_endpoint1 as $data) {
foreach ($api_endpoint2 as $data2) {
$merged_data[] = array_merge($data, $data2[$data['Name']]);
}
}
var_dump($merged_data);
It doesn't work as I tried so many things the past two days, I came to search for help.
Huge thanks to #barrycarter for his help in pushing me into the right direction.
The actual code needed to be like this:
$url1 = 'gameinfo.albiononline.com/api/…';
$url2 = 'gameinfo.albiononline.com/api/…';
$url3 = 'gameinfo.albiononline.com/api/…';
$url4 = 'gameinfo.albiononline.com/api/…';
$url5 = 'gameinfo.albiononline.com/api/…';
$merged_urls = [$url1, $url2, $url3, $url4, $url5];
$api_endpoint = [];
foreach ($merged_urls as $urls) {
$api_endpoint[] = file_get_contents($urls);
}
// Gives all DATA from all Guilds members
// var_dump($api_endpoint);
$merged_arrays = array_merge(json_decode($api_endpoint[0], true), json_decode($api_endpoint[1], true), json_decode($api_endpoint[2], true), json_decode($api_endpoint[3], true), json_decode($api_endpoint[4], true));
foreach ($merged_arrays as $query) {
echo $query['Name'];
echo '<br>';
}
Related
Is there a way I can Array_chunk mysqli results, I am looping messages from a table and later pass the values into a method "Sms" The method will create a List of Sms objects which I pass through a function SendBatchSMS. my API end points can only allow 100 call per request.
I have tried array chunking the list into "$sms" which seams to work well when I print_r($sms), but when echo the response, it returns only 48/249 responses regardless of the size specified in the array_chunk function. My question is, is there a better option to achieve this, something like array_chunking the mysqli results instead of the array list?
$query_sch = "SELECT * FROM ct_queue";
$sch_result = mysqli_query($mysqli, $query_sch);
$rows[] = mysqli_fetch_array($sch_result);
$count = mysqli_num_rows($sch_result);
foreach($sch_result as $value)
{
$phone = $value['phone'];
$sender = $value['sender'];
$message = $value['message'];
$user_id = $value['user_id'];
$link_id = NULL;
$correlator = 'correlator_string';
$endpoint = 'example.com';
$token = "token_string";
// $list = array();
$version = "v1"; //DONT change unless you are using a different version
$instance = new BonTech($token, $version);
$list[] = new Sms($sender, $phone, $message, $correlator, null, $endpoint);
}
$row_chunks = array_chunk($list, 100);
foreach ($row_chunks as $chunk){
$sms = array();
////////here we have 100 messages on each chunk
///////Loop through the messages in side the chunk
foreach ($chunk as $row) {
$sms[] = ($row);
}
// print_r($sms);
}
$response = call_user_func_array(array($instance, "sendBatchSMS"), $sms);
$response = json_encode($response, true);
$results = json_decode($response, true);
print_r($response);
You're using $sms after the foreach loop is done. So it will only contain the last chunk. You need to use it inside the loop.
There's also no need to use a loop to copy $chunk to $sms.
You're also skipping the first row of results because of your call to mysqli_fetch_array($sch_result) before the first foreach loop.
$instance doesn't seem to be dependent on $value, so it shouldn't be in the foreach loop.
$query_sch = "SELECT * FROM ct_queue";
$sch_result = mysqli_query($mysqli, $query_sch);
$list = array();
foreach($sch_result as $value)
{
$phone = $value['phone'];
$sender = $value['sender'];
$message = $value['message'];
$user_id = $value['user_id'];
$link_id = NULL;
$correlator = 'correlator_string';
$endpoint = 'example.com';
$list[] = new Sms($sender, $phone, $message, $correlator, null, $endpoint);
}
$token = "token_string";
$version = "v1"; //DONT change unless you are using a different version
$instance = new BonTech($token, $version);
$row_chunks = array_chunk($list, 100);
foreach ($row_chunks as $sms){
$response = call_user_func_array(array($instance, "sendBatchSMS"), $sms);
print_r($response);
}
I've been trying to run CURL in a foreach loop to extract information from the cryptocompare.com API. As soon as I call the following function, my code just stops working. There is no output.
$fullArray[$symbol]['Price'] = getThePrice($fullArray[$symbol]['Symbol']);
What am I doing wrong? I pasted the code below
include 'helper.php';
$fullArray = array();
//Get List of All Coins and store symbol and ID
$url = "https://min-api.cryptocompare.com/data/all/coinlist";
$jsonArray = getConnection($url);
foreach($jsonArray['Data'] as $value)
{
$symbol = $value['Symbol'];
$fullArray[$symbol]['Symbol'] = $value['Symbol'];
$fullArray[$symbol]['Id'] = $value['Id'];
//call getThePrice function to get Price of ticker
$fullArray[$symbol]['Price'] = getThePrice($fullArray[$symbol]['Symbol']);
}
function getThePrice($input)
{
//Get current price of each coin and store in full array
$url = "https://www.cryptocompare.com/api/data/coinsnapshot/?fsym=".$input."&tsym=USD";
$jsonNewArray = getConnection($url);
if(array_key_exists('PRICE',$jsonNewArray['Data']['AggregatedData']))
{
$returnVariable = $jsonNewArray['Data']['AggregatedData']['PRICE'];
echo "The price of : ".$input." is ".$returnVariable;
}
else{
$returnVariable = "NA";
echo "This price is not available";
}
return $returnVariable;
}
The code in helper.php:
function getConnection($inputHelp)
{
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,$inputHelp);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
//curl_setopt($ch,CURLOPT_CONNECTTIMEOUT, 4);
$json = curl_exec($ch);
if(!$json) {
echo curl_error($ch);
}
curl_close($ch);
$jsonArray = json_decode($json, true);
return $jsonArray;
}
Appreciate any help. Thanks in advance.
I am trying to read a reddit json using my account as an example.
Tried the solution above as:
$string_reddit = file_get_contents("https://www.reddit.com/user/joshfolgado/about.json");
$json = json_decode($string_reddit, true);
$children = $json['data'];
foreach ($children as $child){
$linkkarma = $child['data']['link_karma'];
}
Also tried:
foreach ($json->data as $mydata){
$values["Latest_Karma"] = $mydata['link_karma'];
}
Also tried:
$opts = array(
'http'=>array(
'method'=>"GET",
'header'=>"User-Agent: reddiant api script\r\n"
));
$context = stream_context_create($opts);
$url = "http://www.reddit.com/user/joshfolgado/about.json";
$json = file_get_contents($url, false, $context);
$result = json_decode($json, true);
foreach ($result as $child){
$values['Latest_Karma'] = $child['data']['link_karma'];
}
Spent a couple of hours trying do get the values for any of the items inside the "data" array, havent been able to get any.
What am I doing wrong? What am I missing?
Any help is appreciated.
Thanks
$string_reddit = file_get_contents("http://www.reddit.com/user/joshfolgado/about.json");
$json = json_decode($string_reddit, true);
$children = $json['data'];
foreach ($children as $child){
$link_karma= $child['link_karma'];
}
A slight modification to pee2pee's post (His returned an undefined index error for me)
$string_reddit = file_get_contents("http://www.reddit.com/user/joshfolgado/about.json");
$json = json_decode($string_reddit, true);
$children = $json['data'];
$user = [];
foreach ($children as $key => $value)
{
$user[$key] = $value;
}
echo $user['name']; //Now you can use the $user array to access all the properties!
This works for me ->
I am attempting to fetch JSON from Instagram according to a number of URL parameters, the JSON is then decoded and then the objects required are then encoded into my own JSON format. Whilst I know this sound a little ridiculous, it is what is required. My only issue here is that for some reason it does not encode each section of JSON, it will only work for one item. The code is as below.
<?php
function instagram($count=16){
$igtoken = $_GET['igtoken'];
$hashtag = $_GET['hashtag'];
$url = 'https://api.instagram.com/v1/tags/'.$hashtag.'/media/recent/?access_token='.$igtoken.'&count='.$count;
$jsonData = json_decode((file_get_contents($url)));
$jsonData = json_decode((file_get_contents($url)));
foreach ($jsonData->data as $key=>$value) {
$response = array();
$response["data"] = array();
$data = array();
$data["createdtime"] = $value->caption->created_time;
$data["username"] = $value->caption->from->username;
$data["profileimage"] = $value->caption->from->profile_picture;
$data["caption"] = $value->caption->text;
$data["postimage"] = $value->images->standard_resolution->url;
array_push($response["data"], $data);
$result = json_encode($response);
}
return $result;
}
echo instagram();
?>
It will work for each section of JSON if I do something like this instead:
$result .= '<li>
'.$value->caption->from->username.'<br/>
'.$value->caption->from->profile_picture.'<br/>
'.$value->caption->text.'<br/>
'.$value->images->standard_resolution->url.'<br/>
'.$value->caption->created_time.'<br/>
</li>';
I feel I have bodged up somewhere with the array, however i'm not entirely sure.
What if we move $response["data"] and $result varia out of foreach?
Have you tried this?
$response = array();
$response["data"] = array();
foreach ($jsonData->data as $key=>$value) {
$data = array();
$data["createdtime"] = $value->caption->created_time;
$data["username"] = $value->caption->from->username;
$data["profileimage"] = $value->caption->from->profile_picture;
$data["caption"] = $value->caption->text;
$data["postimage"] = $value->images->standard_resolution->url;
array_push($response["data"], $data);
}
$result = json_encode($response);
return $result;
I have the following PHP code that I am using to pull Tweets:
<?php
class TwitterFeed {
public $tweets = array();
public function __construct($user, $limit = 5) {
$user = str_replace(' OR ', '%20OR%20', $user);
$feed = curl_init('http://search.twitter.com/search.atom?q=from:'. $user .'&rpp='. $limit);
curl_setopt($feed, CURLOPT_RETURNTRANSFER, true);
curl_setopt($feed, CURLOPT_HEADER, 0);
$xml = curl_exec($feed);
curl_close($feed);
$result = new SimpleXMLElement($xml);
foreach($result->entry as $entry) {
$tweet = new stdClass();
$tweet->id = (string) $entry->id;
$user = explode(' ', $entry->author->name);
$tweet->user = (string) $user[0];
$tweet->author = (string) substr($entry->author->name, strlen($user[0])+2, -1);
$tweet->title = (string) $entry->title;
$tweet->content = (string) $entry->content;
$tweet->updated = (int) strtotime($entry->updated);
$tweet->permalink = (string) $entry->link[0]->attributes()->href;
$tweet->avatar = (string) $entry->link[1]->attributes()->href;
array_push($this->tweets, $tweet);
}
unset($feed, $xml, $result, $tweet);
}
public function getTweets() { return $this->tweets; }
}
$feed = new TwitterFeed('trekradio', 4);
$tweets = $feed->getTweets();
?>
I need to replace 'trekradio' in this line $feed = new TwitterFeed('trekradio', 4); so that it uses the following code. This code defines the Twitter ID on a Dynamic Basis from a Database Field.
<?php if (have_posts()) { $flag = true; while (have_posts()) { the_post();
if ($flag) { $value = get_cimyFieldValue(get_the_author_ID(), 'twitter-username');
if ($value != NULL) echo . cimy_uef_sanitize_content($value) . ;
$flag = false; }}} ?>
Can someone show me how to integrate the code so that it will properly function?
Thanks
The assumption I am making is that $value is the variable you will want to send through as the parameter?
I'm also assuming that the TwitterFeed class is accessible from where you are trying to run the second snippet of code.
The final assumption is that cimy_uef_sanitize_content returns a value that is valid to be passed as the parameter to the TwitterFeed constructor.
Remove the $feed and $tweets line from below the class (unless you explicitly require it to be run against trekradio).
Then use the following code:
<?php
if (have_posts()) {
$flag = true;
while (have_posts()) {
the_post();
if ($flag) {
$value = get_cimyFieldValue(get_the_author_ID(), 'twitter-username');
if ($value != NULL) {
$feed = new TwitterFeed(cimy_uef_sanitize_content($value), 4);
$tweets = $feed->getTweets();
// Do whatever you need to do with your Tweets here
}
$flag = false;
}
}
} ?>
But why are you asking this question again? It was surely already answered in
PHP - An Echo inside of an existing function
EDIT: Question: What is the difference between 'twitter-username' and the value you want to send to the $user parameter in your TwitterFeed constructor? If these are the same it could be simplified.