So I got the next output from a print_r
Coinbase\Wallet\Value\Money Object
(
[amount:Coinbase\Wallet\Value\Money:private] => 18945.00
[currency:Coinbase\Wallet\Value\Money:private] => USD
)
I'm using Coinbase SDK -> link to github
My question is how am I supposed to read the amount value?
I'm generating that using
$buyPrice = $client->getSpotPrice('BTC-USD');
and getSpotPrice function is ->
public function getSpotPrice($currency = null, array $params = [])
{
if (strpos($currency, '-') !== false) {
$pair = $currency;
} else if ($currency) {
$pair = 'BTC-' . $currency;
} else {
$pair = 'BTC-USD';
}
return $this->getAndMapMoney('/v2/prices/' . $pair . '/spot', $params);
}
saw something like this in the test integrations but I can't tell how to make this work:
public function testGetSpotPrice1()
{
$price = $this->client->getSpotPrice();
$this->assertInstanceOf(Money::class, $price);
}
Any help/ideas will be appreciated , thank you!
Once you've got the value by
$buyPrice = $client->getSpotPrice('BTC-USD');
You can then use (from the source https://github.com/coinbase/coinbase-php/blob/master/src/Value/Money.php )...
$amount = $buyPrice->getAmount();
$currency = $buyPrice->getCurrency();
$BTCSellPrice = $client->getSpotPrice('BTC-USD');
//this is what you are looking for
$BTCUSD = $BTCSellPrice->getAmount();
Related
Country.csv
this is countries.csv file, and i want to extract all the timezones from it, which is its 14th colomn, and the data in there is not properly json formatted. I'm trying to parse the json but it failed. Actually, I want to create an array of timezones like this
[0] => {zoneName:'Asia -> Kabul',gmtOffset:16200,gmtOffsetName:'UTC+04:30',abbreviation:'AFT',tzName:'Afghanistan Time'}
[1] => {zoneName:'Europe -> Mariehamn',gmtOffset:7200,gmtOffsetName:'UTC+02:00',abbreviation:'EET',tzName:'Eastern European Time'}
[2] => {zoneName:'Europe -> Tirane',gmtOffset:3600,gmtOffsetName:'UTC+01:00',abbreviation:'CET',tzName:'Central European Time'}
[3] => {zoneName:'Africa -> Algiers',gmtOffset:3600,gmtOffsetName:'UTC+01:00',abbreviation:'CET',tzName:'Central European Time'}
[4] => {zoneName:'Pacific -> Pago_Pago',gmtOffset:-39600,gmtOffsetName:'UTC-11:00',abbreviation:'SST',tzName:'Samoa Standard Time'}
[5] => {zoneName:'Europe -> Andorra',gmtOffset:3600,gmtOffsetName:'UTC+01:00',abbreviation:'CET',tzName:'Central European Time'}
[6] => {zoneName:'Africa -> Luanda',gmtOffset:3600,gmtOffsetName:'UTC+01:00',abbreviation:'WAT',tzName:'West Africa Time'}
what i'm doing, is this in App\Http\Controllers\TestController::class is this
public function timezone(): void {
$data = [];
if (($open = fopen(__DIR__ . '/countries.csv', 'r + b')) !== FALSE) {
while (($singleRecord = fgetcsv($open, NULL, ',')) !== FALSE) {
$data[] = $singleRecord;
}
fclose($open);
}
$data = $this->removeCharacters($data, ['[', ']']);
$data = $this->removeCharacters($data, (array)'\/', " -> ");
// $data = $this->removeCharacters($data, (array)'{}', '');
// dd(explode('},', $data[33][14]));
// dd(explode('},', $this->longJson));
// dd(explode(',', str_replace(['{', '}'], '', $data[167][14])));
$singleArray = [];
$count = count($data);
$itemsArray = [];
for ($i = 1; $i < $count; $i++) {
$singleArray[] = explode('},', $data[$i][14]);
foreach ($singleArray as $item) {
foreach ($item as $singleItem) {
$itemsArray[] = $singleItem;
}
}
}
$itemsArray = array_unique($itemsArray);
$this->printFormattedData($itemsArray);
}
private function removeCharacters($hayStack, array $charsArray, $character = ''): array {
$tempArray = [];
foreach ($hayStack as $item) {
$tempArray[] = str_replace($charsArray, $character, $item);
}
return $tempArray;
}
private function printFormattedData($data): void {
echo '<pre>';
print_r($data);
echo '</pre>';
}
Using regexp its not perfect solution, but you can transform timezone data to correct json format using function like this:
public function fixJson(string $str): string {
return preg_replace(
'/(?<=(\{|\,))(\w+)(?=\:)/',
'"$2"',
str_replace("'", '"', $zoneRaw) // may not work properly, if values may contain apostroph symbols, but seems not actual for your case
);
}
So, use this function:
$this->fixJson($data[$i][14]); // returns json string
json_decode($this->fixJson($data[$i][14])); // returns json decoded array
See usage example here https://sandbox.onlinephpfunctions.com/c/88f21
Following code would do, what you aim.
Please do not forget to mark this answer as ACCEPTED and thumbs up if it solves your problem, so that the work of the developers who help is appreciated and other developers can see in question list, that your question has already an accepted answer.
$lines = file("countries.csv");
array_shift($lines); // remove the first line with column names
$searchReplace = ['\/' => '->'];
$search = array_keys($searchReplace);
$replace = array_values($searchReplace);
$jsonFormattedTimeZones = [];
foreach($lines as $line)
{
$line = trim(str_getcsv($line)[14], " []");
$line = str_replace($search, $replace, $line);
$jsonFormattedTimeZones[] = $line;
}
print_r($jsonFormattedTimeZones);
I can get the not-bind query on with this way :
\DB::enableQueryLog();
$items = OrderItem::where('name', '=', 'test')->get();
$log = \DB::getQueryLog();
print_r($log);
Output is :
(
[0] => Array
(
[query] => select * from "order_items" where "order_items"."name" = ? and "order_items"."deleted_at" is null
[bindings] => Array
(
[0] => test
)
[time] => 0.07
)
)
But what I really need is bind query like this :
select * from "order_items" where "order_items"."name" = 'test' and "order_items"."deleted_at" is null
I know I can do this with raw PHP but is there any solution in laravel core?
Actually I've created one function within helpers.php for same. You can also use same function within your helpers.php file
if (! function_exists('ql'))
{
/**
* Get Query Log
*
* #return array of queries
*/
function ql()
{
$log = \DB::getQueryLog();
$pdo = \DB::connection()->getPdo();
foreach ($log as &$l)
{
$bindings = $l['bindings'];
if (!empty($bindings))
{
foreach ($bindings as $key => $binding)
{
// This regex matches placeholders only, not the question marks,
// nested in quotes, while we iterate through the bindings
// and substitute placeholders by suitable values.
$regex = is_numeric($key)
? "/\?(?=(?:[^'\\\']*'[^'\\\']*')*[^'\\\']*$)/"
: "/:{$key}(?=(?:[^'\\\']*'[^'\\\']*')*[^'\\\']*$)/";
$l['query'] = preg_replace($regex, $pdo->quote($binding), $l['query'], 1);
}
}
}
return $log;
}
}
if (! function_exists('qldd'))
{
/**
* Get Query Log then Dump and Die
*
* #return array of queries
*/
function qldd()
{
dd(ql());
}
}
if (! function_exists('qld'))
{
/**
* Get Query Log then Dump
*
* #return array of queries
*/
function qld()
{
dump(ql());
}
}
Simply place these three functions within your helpers.php file and you can use same as follows:
$items = OrderItem::where('name', '=', 'test')->get();
qldd(); //for dump and die
or you can use
qld(); // for dump only
Here I extended the answer of #blaz
In app\Providers\AppServiceProvider.php
Add this on boot() method
if (env('APP_DEBUG')) {
DB::listen(function($query) {
File::append(
storage_path('/logs/query.log'),
self::queryLog($query->sql, $query->bindings) . "\n\n"
);
});
}
and also added a private method
private function queryLog($sql, $binds)
{
$result = "";
$sql_chunks = explode('?', $sql);
foreach ($sql_chunks as $key => $sql_chunk) {
if (isset($binds[$key])) {
$result .= $sql_chunk . '"' . $binds[$key] . '"';
}
}
$result .= $sql_chunks[count($sql_chunks) -1];
return $result;
}
Yeah, you're right :/
This is a highly requested feature, and i have no idea why its not a part of the framework yet...
This is not the most elegant solution, but you can do something like this:
function getPureSql($sql, $binds) {
$result = "";
$sql_chunks = explode('?', $sql);
foreach ($sql_chunks as $key => $sql_chunk) {
if (isset($binds[$key])) {
$result .= $sql_chunk . '"' . $binds[$key] . '"';
}
}
return $result;
}
$query = OrderItem::where('name', '=', 'test');
$pure_sql_query = getPureSql($query->toSql(), $query->getBindings());
// Or like this:
$data = OrderItem::where('name', '=', 'test')->get();
$log = DB::getQueryLog();
$log = end($log);
$pure_sql_query = getPureSql($log['query'], $log['bindings']);
You can do that with:
OrderItem::where('name', '=', 'test')->toSql();
I have encountered the following error
Undefined property: stdClass::$account_id (View:
C:\xampp\htdocs\laravel\awsconfig\app\views\search.blade.php)
here is the code which is causing this error :
$resource_types = array();
$resource_types['AWS::EC2::Instance'] = 'EC2Instance';
$resource_types['AWS::EC2::NetworkInterface'] = 'EC2NetworkInterface';
$resource_types['AWS::EC2::VPC'] = 'VPC';
$resource_types['AWS::EC2::Volume'] = 'Volume';
$resource_types['AWS::EC2::SecurityGroup'] = 'EC2SecurityGroup';
$resource_types['AWS::EC2::Subnet'] = 'Subnet';
$resource_types['AWS::EC2::RouteTable'] = 'RouteTable';
$resource_types['AWS::EC2::EIP'] = 'EIP';
$resource_types['AWS::EC2::NetworkAcl'] = 'NetworkAcl';
$resource_types['AWS::EC2::InternetGateway'] = 'InternetGateway';
$accounts = DB::table('aws_account')->get();
$account_list = array();
foreach(glob('../app/views/*.json') as $filename)
{
//echo $filename;
$data = file_get_contents($filename);
if($data!=null)
{
$decoded=json_decode($data,true);
if(isset($decoded["Message"]))
{
//echo "found message<br>";
$message= json_decode($decoded["Message"]);
if(isset($message->configurationItem))
{
// echo"found cfi<br>";
$insert_array = array();
$cfi = $message->configurationItem;
switch ($cfi->configurationItemStatus)
{
case "ResourceDiscovered":
//echo"found Resource Discovered<br>";
if (array_key_exists($cfi->resourceType,$resource_types))
{
//var_dump($cfi->resourceType);
$resource = new $resource_types[$cfi->resourceType];
foreach ($cfi->configuration as $key => $value)
{
if (in_array($key,$resource->fields))
{
$insert_array[from_camel_case($key)] = $value;
}
}
$resource->populate($insert_array);
if (!$resource->checkExists())
{
$resource->save();
if(isset($cfi->configuration->tags))
{
foreach ($cfi->configuration->tags as $t )
{
$tag= new Tag;
$tag->resource_type = "instance";
$tag->resource_id = $resource->id;
$tag->key = $t->key;
$tag->value = $t->value;
$tag->save();
if(isset($cfi->awsAccountId))
{
foreach ($accounts as $a)
{
$account_list[] = $a->account_id;
}
if (!in_array($account_id,$account_list))
{
$account_id = new Account;
$account_id->aws_account_id = $cfi->awsAccountId;
$account_list[] = $account_id;
$account_id->save();
}
}
}
}
}
}
else
{
echo "Creating ".$cfi["resourceType"]." not yet supported<br>";
}
break;
I know it will be something silly I appreciate all help as always thanks
Base on your code this is a simple demonstartion i am explanning, DB::select will returns a array which contains several objects (may be more than one), and then you assign it to$this->food.
Remember, the $this->food looks like
Array (
[0] => stdClass Object (
[name] => 'Beef'
)
)
Actually, $this->food->name is trying to access a undefined property.
Solution 1:
You should use $this->food[0]->name to access it.
Thought it looks weird, but it works.
Solution 2:
Why not call Food::find($id) to fetch the object instead of $food = new food($id)
You can learn more by reading this http://laravel.com/docs/eloquent
Hope this might help you in solving your problem
I am trying to get a response from my json array:
stdClass Object ( [Foo] => stdClass Object ( [id] => 0001 [name] => Foo [profileIconId] => 550 [summonerLevel] => 30 [revisionDate] => 1408463933000 ) )
using my current code, I know that it is really easy to solve - but I don't know what I am doing wrong as I can't find anything similar to this from what I am searching:
api.php:
<?php
class runeapi {
const get_id_na = 'https://na.api.pvp.net/api/lol/na/v1.4/summoner/by-name/';
const get_id_euw = 'https://euw.api.pvp.net/api/lol/euw/v1.4/summoner/by-name/';
const key = '...';
public function getID($summoner_name) {
$name = $summoner_name;
$call = self::get_id_euw .$name;
return $this->request($call);
}
private function request($call) {
$url = $call. '?api_key=' .self::key;
$json = file_get_contents($url);
$decode = json_decode($json);
$result = $decode; //<-- This is the Issue.
return $result;
}
}
?>
testing.php:
<?php
include('api.php');
$summoner_name = 'Foo';
$test = new runeapi;
$r = $test->getID($summoner_name);
print_r($r);
?>
$r returns $result
I'd like to be able to call for id but no matter where I tried looking, I couldn't find an example similar to what I have.
What I've tried:
$decode->{'id'};
$decode{'id'};
I believe this will work for you
private function request($call) {
$url = $call. '?api_key=' .self::key;
$json = file_get_contents($url);
return $json;
}
No need to decode it.
I had to add another variable to request():
public function getID($summoner_name) {
$name = $summoner_name;
$call = self::get_id_euw .$name;
return $this->request($call, $name); //<-- added $name
}
private function request($call, $name) { //<-- added $name
$url = $call. '?api_key=' .self::key;
$json = file_get_contents($url);
$decode = json_decode($json);
$result = $decode->{$name}->{'id'}; //<-- added $name
return $result;
}
is there a way to achieve this in PHP?
echo list_args('a_user_defined_function_name_here_such_as_say_hello');
and this outputs something like
$first_name
$last_name
for a function defined as;
function say_hello($first_name, $last_name){
echo "Hello $first_name $last_name";
}
So basically, what I'm looking for is a function explainer or something of that sort... & if that thing can get into a php doc based comment extractor. that would be even better..
You could use the ReflectionFunction class to do this:
function list_args($name) {
$list = "";
$ref = new ReflectionFunction($name);
foreach ($ref->getParameters() as $param) {
$list .= '$' . $param->getName() . "\n";
}
return $list;
}
You can try ReflectionFunction.
function list_args($function) {
$func = new ReflectionFunction($function);
$res = array();
foreach ($func->getParameters() as $argument) {
$res[] = '$' . $argument->name;
}
return $res;
}
print_r(list_args('say_hello')); // outputs Array ( [0] => $first_name [1] => $last_name )