Hello fellow developers,
I have been trying to manipulate the output and display the total amount of workers there are instead of outputting the workers name as a string.
Bellow you will find the data that i am receiving and further down i will explain how i would like to handle the JSON response.
{
"result":
{
"addr":"ADDRESS_HERE",
"workers":
[
["worker1080",{},2,1,"200000",0,22],
["worker1080",{"a":"899.4"},3,1,"512",0,24]
],
"algo":-1
},
"method":"stats.provider.workers"
}
So basically as you can see from the above response that there are 2 workers named "worker1080" active on that address.
The bellow php code is how i retrieve the data and output only the names of the workers:
<?php
$btcwallet = get_btc_addy();
if (isset($cur_addy)) {
$method4 = new methods();
$worker_stats = new urls();
$get_data = file_get_contents(utf8_encode($worker_stats->nice_url.$method4->m4.$cur_addy));
$get_json = json_decode($get_data, true);
foreach ($get_json['result']['workers'] as $v) {
$i = 0;
print $v[$i++]."<br />";
}
}
?>
$get_json is the variable that decodes the data from $get_data and displays the worker names and increments every time a worker is added or online.
now i currently have 2 workers online as shown in the JSON response.
it outputs:
worker1080
worker1080
which is perfect although if i try using a foreach statement and try to display the the total amount of workers online it should display 2 instead of the names, it has to also increment for each worker that the json repsonse outputs.
EG: i have 2 workers online now, but in an hour i will connect 10 more it would display the following:
worker1080
worker1080
worker1070
worker1070
worker1080ti
worker1080ti
workerASIC
workerASIC
workerASIC
workerCPU
workerCPU
workerCPU
Now i try to use the following to display the total:
count($v[$i++]);
and i have tried using a foreach within the foreach, and both count and the foreach both will either display "0" by all the workers or "1"
bellow is an example of the output.
0
0
0
0
0
How would i go about counting each line in the output and display the total number of workers ?
Thanks #symcbean for the solution.
<?php
$btcwallet = get_btc_addy();
if (isset($cur_addy)) {
$method4 = new methods();
$worker_stats = new urls();
$get_data = file_get_contents(utf8_encode($worker_stats->nice_url.$method4->m4.$cur_addy));
$get_json = json_decode($get_data, true);
print count($get_json['result']['workers'])."<br />"; // <-- solution *removed foreach and $i incrementation as its not needed for count
}
?>
it now displays the correct number of workers :)
Related
I am attempting to scrape the price of the same product from two different websites. While it pulls the correct results and prints out what I want, when the I run the script I get this error after the results are correctly printed:
Fatal error: Maximum execution time of 120 seconds exceeded in [...] on line 144
And this is my code:
<?php
//Adds in the simple HTML DOM parser
include ('simple_html_dom.php');
//Defines the Target URL to Scrape
$cbdUrl = "https://cbdstore.co.za/product/africanpure-everyday-cbd-1000mg-30ml/";
$apUrl = "https://africanpure.co/product/everyday-cbd-oil-1000mg-30ml/";
//Defines 'html' as the scraped content from the URL above
$cbdHtml = file_get_html($cbdUrl);
$apHtml = file_get_html($apUrl);
//Creating an array to store all the 'price' classes text from the page
$cbdPrices = array();
//Fetching all the '.amount' and storying them in the array as plain text.
foreach($cbdHtml->find('div.summary.entry-summary p.price') as $cbdElement)
{
foreach($cbdElement->find('.amount') as $cbdAmt)
{
$cbdPrices [] = $cbdAmt->plaintext;
}
}
//Repeating for AfricanPure
$apPrices = array();
foreach($apHtml->find('div.summary-inner div.basel-scroll-content p.price') as $apElement)
{
foreach($apElement->find('.amount') as $apAmt)
{
$apPrices [] = $apAmt->plaintext;
}
}
// Writes out CBD Store Price
echo 'CBD Store has the Everday CBD Oil for: ' . $cbdPrices[0];
// Writes out AP Price
echo 'African Pure has the Everday CBD Oil for: ' . $apPrices[0];
?>
It looks like you are only interested in one price for each ($cbdPrices[0]) and not an array of prices, so try breaking out of the loops after getting the first price.
foreach($cbdHtml->find('div.summary.entry-summary p.price') as $cbdElement)
{
foreach($cbdElement->find('.amount') as $cbdAmt)
{
$cbdPrices [] = $cbdAmt->plaintext;
break;
}
}
And do the same on the other one. You could also probably not make the variable an array in the first place?
I have a URL that returns a JSON object like this:
{
"USD" : {"15m" : 7809.0, "last" : 7809.0, "buy" : 7809.85, "sell" : 7808.15, "symbol" : "$"},
"AUD" : {"15m" : 10321.42, "last" : 10321.42, "buy" : 10322.54, "sell" : 10320.3, "symbol" : "$"},
}
URL : https://blockchain.info/ticker
more info : https://blockchain.info/api/exchange_rates_api
I want to get all the data from the first line and echo it and to have it keep requesting it so its live
I have used the examples on git hub
https://github.com/blockchain/api-v1-client-php/blob/master/docs/rates.md
but it displays all of the data output and you have to refresh it to get it updated
please can some one point me in the right direction
ideally I would end up with something like
15 m Last Buy Sell
USD ($) 7794.87 7794.87 7795.72 7794.02
I have the table and data going to the table but its echoing the whole data set rather than the first line and also I dont know how to select individual fields
How can I do it through PHP?
What you need is a request php page, which will make:
1 - Get data from te site:
$data = file_get_contents('https://blockchain.info/ticker');
2 - decode the json
$decodedData = json_decode($data);
3 - Here you can access it using OOP:
var_dump($decodedData->USD);
The point here will be to retrieve data as you wish, you can mix it up with HTML in a table for example.
Then, you need a JS script, that will execute a function with setInterval, each few miliseconds. That function should make a request to a PHP page that you created earlier, get that data and change with the updated one.
This Should do it:
<?
$seconds = 5;
function get_live_quote($key){
$json_string = file_get_contents('https://blockchain.info/ticker');
$json_array = json_decode($json_string, TRUE);
$quote = $json_array[$key];
$keys = implode(" ",array_keys($quote));
$values = implode(" ", array_values ($quote));
return "$keys $values \n";
}
while(TRUE){
echo get_live_quote("USD");
sleep($seconds);
}
Save the preceding code to a file like "quote.php". Then from your terminal just run: php quote.php
Hello I am trying to extract some info from a json format page
The page is : https://blockchain.info/fr/rawaddr/1BQLNJtMDKmMZ4PyqVFfRuBNvoGhjigBKF
this link allows to get all bitcoin transactions from an address.
All the quotation marks confuse me, I can not see clearly
I want to display everything like the original blockchain website
Blockchain Display view
The beginning will be something like that
$json = file_get_contents("https://blockchain.info/fr/rawaddr/1BQLNJtMDKmMZ4PyqVFfRuBNvoGhjigBKF");
var_dump(json_decode($json));
I can extract basic info from JSO to php, but here there is too much transactions and I think we need to use a loop to display everything but I don't know how to do that
If someone can display for me in php the 5 first transactions it will be very sympathic.
Thanks a lot in advance youw ill really help me if you can do that !
If you goal is to display all Tx info you want to do that.
$json = file_get_contents("http://blockchain.info/fr/rawaddr/1BQLNJtMDKmMZ4PyqVFfRuBNvoGhjigBKF");
$txs = json_decode($json,1)['txs'];
echo"<pre>"; //just to get a human readable display
foreach($txs as $txinfo){
echo"A new tx";
//will display the full tx data
print_r($txinfo);
}
echo"</pre>";
Note a blockchain transaction can be a little complexe since one transaction can have multiple input and multiple outputs.
you might want to cycle trough outputs as well to display all addresses who received bitcoin from a transaction
in that case you can simply add another foreach output
$json = file_get_contents("http://blockchain.info/fr/rawaddr/1BQLNJtMDKmMZ4PyqVFfRuBNvoGhjigBKF");
$txs = json_decode($json,1)['txs'];
echo"<pre>"; //just to get a human readable display
foreach($txs as $txinfo){
echo"A new tx";
//will display the full tx data
print_r($txinfo);
// will cycle trough all output for each tx
foreach ($txinfo['out'] as $outgoingTransaction)
{
//Will display the receiving address
$receivingAddress = $outgoingTransaction['addr'];
//will get the amount sent in satoshis
$receivingAmountInSatoshi = $outgoingTransaction['value'];
echo"<br>1BQLNJtMDKmMZ4PyqVFfRuBNvoGhjigBKF sent to $receivingAddress $receivingAmountInSatoshi satoshis <br>";
}
}
a more advanced code to add tx understanding logic
$walletAddress = '1AWKFrvFYuCC7ef2m2zX73pWu1C15FRGjR' ;
$json = file_get_contents("http://blockchain.info/fr/rawaddr/$walletAddress");
$txs = json_decode($json,1)['txs'];
echo"<pre>"; //just to get a human readable display
foreach($txs as $txinfo){
$spendingTx = false ;
$totalSpent = 0 ;
$totalReceived = 0;
echo"<p>Txid = $txinfo[hash]<br>";
//print_r($txinfo);
// we need to find out if the address is the sender or the receiver
$senderData = reset($txinfo['inputs']); //using reset to get only the first input
if ($senderData['prev_out']['addr'] ==$walletAddress ){
//the address is the sender meaning the address is spending
$spendingTx = true ;
}
//it's a spend tx then we cycle trough receivers
if ($spendingTx) {
foreach ($txinfo['out'] as $outgoingTransaction) {
//Will display the receiving address
$receivingAddress = $outgoingTransaction['addr'];
//will get the amount sent in satoshis
$receivingAmountInSatoshi = $outgoingTransaction['value'];
$totalSpent = $totalSpent + $receivingAmountInSatoshi ;
echo "<br>$walletAddress sent to $receivingAddress $receivingAmountInSatoshi satoshis <br>";
}
echo "<br>Total spent = $totalSpent" ;
}
//it is not a spending tx so it's a receceiving tx
else {
foreach ($txinfo['out'] as $outgoingTransaction) {
//We keep only receiving data concerning current wallet
if ($outgoingTransaction['addr'] == $walletAddress) {
//Will display the receiving address
$receivingAddress = $outgoingTransaction['addr'];
//will get the amount sent in satoshis
$receivingAmountInSatoshi = $outgoingTransaction['value'];
$senderAddress = $senderData['prev_out']['addr'];
$totalReceived = $receivingAmountInSatoshi;
echo "<br>$walletAddress received $receivingAmountInSatoshi satoshis from $senderAddress<br>";
}
}
echo "<br>Total received = $totalReceived" ;
}
echo"<br>end tx </p>";
}
echo"</pre>";
I want to compare the time between sent messages, so that i know how quick someone would respond.
message_sent is the unix timestamp when a message has been sent.
ID: 0000000005 is the start, ID: 0000000006 is a response on the message of ID: 0000000005.
With this data: 0000000006 sent a message on 1483021773. The original question was asked in 0000000005 on 1483021687. So the reaction time is 1483021773 - 1483021687. How should i approach this so i get an average response time?
The data
Assuming that a response time is defined by the time it takes for a user to respond to the last message of another user:
$response_times = array(); // array of response times
// let's define a variable to keep track of the person
// to which another person will respond. initially, variable will hold
// the first message
$initiator = array_shift($messages);
// now iterator through messages
foreach ($messages as $message) {
// if this message belongs to the initiator, just update the timestamp
if ($message['from_user_id'] == $initiator['from_user_id']) {
$initiator['message_sent'] = $message['message_sent'];
continue; // and go to the next message
}
// otherwise, calculate the time difference and put it in response times
array_push($response_times, $message['message_sent'] - $initiator['message_sent']);
// and update the initiator
$initiator = $message;
}
// finally, calculate average of response time
$avg_response_time = array_sum($response_times) / count($response_times);
Since i don't know the exact code here is some sudo code with an example:
$total_items = count($array_of_items);
$starting_time_total = "0";
// Some code here to do your message_sent - message_sent = $some_value;
// Do the following for every single item for the $total_items in array
$starting_time_total = $starting_time_total + $some_value;
//Now to get the average we do this
$average = $starting_time_total / $total_items;
So if you have 4 items in the array, with response times of 423, 395, 283, 583 respectively, you are left with an average response time of 421 which you can then convert to seconds of minutes or whatever.
Thanks in advance for any help offered.
I'm performing a query that returns something like this:
route | busnumber
2 300
4 123
2 455
12 934
My goal is to print/echo a list of all "busnumber" were "route" = 2.
I know I can do a query on the DB to do this but I don't want to run this query for each and every route. The result set is actually part of one master, complex query so I need to accomplish my goal using the array.
The query works correctly and does display the appropriate info. I also return the results into an array. i.e ...
$query=("SELECT * from foo")
$result=mysql_fetch_assoc($query);
My current code looks like this (note my comments):
mysql_data_seek( $result,0); // because I'm previously iterating through $result
while ($i2=mysql_fetch_assoc($result)) {
$busnumber=$i2['busnumber'];
$busroute=$i2['route'];
echo "<div class='businfo'>";
if ($busroute='2'){ // I only want this to happen if $busroute=2
echo "Current Route = $busroute</br>";
echo "Bus Number : $busnumber </br>";
}
echo "</div>";
}
What I'm getting, however, it is echoing the same '$busroute' (2) but different '$busnumber' for each row as such:
Current Route = 2
Bus Number : 194
Current Route = 2
Bus Number : 196
Current Route = 2
Bus Number : 2002
Current Route = 2
Bus Number : 2010
Current Route = 2
Bus Number : 2013
The problem is that all of those bus numbers are not part of route 2. It is a listing of bus numbers from all routes. I only want it to perform the foreach loop if $routenumber=2.
Thanks again for the help :)
if ($busroute='2'){
The problem is that you're not checking whether it's equal to 2 here, you're assigning it to equal 2. Change it to this and you'll be fine:
if ($busroute=='2'){
$query = "SELECT * from foo";
$result = mysql_query($query);
while($row = mysql_fetch_assoc($result)) {
if ($row['route'] == 2) {
// do your stuff
}
}