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;
}
Related
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();
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 don't work with PHP very often, at least not at this level, so I need some help. I have a SOAP response in PHP that turns into an Object:
stdClass Object
(
[Food_Document] => stdClass Object
(
[Food_Type] => Fruit
[Food_Serial] => 923490123
[Food_Name] => Apple
[Food_PictureName] => rotten_apple.jpg
[Food_PictureData] => sdlkff90sd9f90af9903r90wegf90asdtlj34kljtklsmdgkqwe4otksgk
)
)
What I need is the data from Food_PictureName and Food_PictureData, but it explodes with a warning every time I try to access it if it doesn't exist. Some objects will contain Food_PictureName and Food_PictureData, but not all of the time. Sometimes, only one or the other will exist, or neither. Basically, "0 or more times."
Here's the code I'm using:
function get_food_photo($serial)
{
$soap = new SoapClient("WSDL_LINK", array('trace' => true));
$params = new StdClass;
$params->serialNumber = $serial; // or whatever serial number you choose
$res = $soap->GetFoodDocuments($params);
$res = $res->GetFoodDocumentsResult;
$thumbnail_data = $res->FoodDocument[0]->Food_PictureData;
$ext = str_replace('.', '', $res->FoodDocument[0]->Food_PictureExtension);
return '<img src="data:image/'.$ext.';base64,'.$thumbnail_data.'"/>';
}
Now, accessing this data and displaying it DOES work if the Food_PictureData property is not null or empty, but otherwise, it will generate a warning every time: Fatal error: Cannot use object of type stdClass as array
I have tried the following: isset(), empty(), property_exists(), __isset(), strlen(), and some others.
How do I get this data without throwing an exception if it doesn't exist?
Rewrite the function as
function get_food_photo($serial)
{
$soap = new SoapClient("WSDL_LINK", array('trace' => true));
$params = new StdClass;
$params->serialNumber = $serial; // or whatever serial number you choose
$res = $soap->GetFoodDocuments($params);
$res = $res->GetFoodDocumentsResult;
if (is_array($res->FoodDocument)) {
$document = $res->FoodDocument[0];
} else {
$document = $res->FoodDocument;
}
if (property_exists($document, 'Food_PictureData')) {
$thumbnail_data = $document->Food_PictureData;
} else {
$thumbnail_data = '';
}
if (property_exists($document, 'Food_PictureExtension')) {
$ext = str_replace('.', '', $document->Food_PictureExtension);
} else {
$ext = '';
}
return '<img src="data:image/'.$ext.';base64,'.$thumbnail_data.'"/>';
}
In PHP, how to get a JSON value from a variable path ?
Here is a sample json and a function with 2 params: a json variable, and path split into keys.
$myjson = json_decode('{
"myKey1": {
"myKey2": {
"myKey3": {
"myKey4": "myfinalvalue"
}
}
}
}');
function getJSONValue($myjson, $pathkey) {
// split path keys by ";"
$myjson-> ?? $pathkey ??
}
echo getJSONValue($myjson, "myKey1;myKey2;myKey3;myKey4");
// Should display "myfinalvalue"
the static equivalent would be to do:
$myjson->myKey1->myKey2->myKey3->myKey4;
I tried:
$myjson->$pathkey
but unfortunately, it doesn't work...
Actually, your question has nothing to do with JSON. This is how you can get a value from a nested object:
function getValue($obj, $path) {
foreach(explode(';', $path) as $key) {
$obj = $obj->$key;
}
return $obj;
}
As for the JSON part, your example is not a valid JSON. It should be like this:
$myjson = json_decode('{
"myKey1": {
"myKey2": {
"myKey3": {
"myKey4": "myfinalvalue"
}
}
}
}');
Also, php objects are case-sensitive, if you have myKey in the object, it should be myKey (and not mykey) in the path string.
function getJSONValue($myjson, array $pathkey) {
foreach($pathkey as $val){
$myjson = $myjson->{$val};
}
return $myjson;
}
$myjson = json_decode('{"myKey1": {"myKey2": {"myKey3": {"myKey4": "myfinalvalue"}}}}');
echo getJSONValue($myjson, ["myKey1","myKey2","myKey3","myKey4"]);
live example: http://codepad.viper-7.com/1G78Fi
Something like this:
function getJSONValue() {
$args = func_get_args();
$json = array_shift($args);
$key = array_shift($args);
$value = $json->$key;
if(is_object($value)) {
array_unshift($args, $value);
return call_user_func_array('getJSONValue', $args);
}
return $value;
}
No error checking.
Seems like you are mixing PHP and JS. check this out to see how to create a Json string, then getting an onject out of it, and accessing keys:
$myjson = json_encode(array(
'myKey1' => array(
'mykey2' => array(
'mykey3' => array(
'myKey4' => "myfinalvalue"
)
)
)
));
$obj = json_decode($string);
echo $obj->myKey1->mykey2->mykey3->myKey4
// "myfinalvalue"
or pasting the json directly:
$obj = json_decode(
'{
myKey1: {
mykey2: {
mykey3: {
myKey4: "myfinalvalue"
}
}
}
}');
echo $obj->myKey1->mykey2->mykey3->myKey4
// "myfinalvalue"
To understand it betterm, read about JSON_DECODE
I have the below php code which outputs me a json array from freebase api.
<?php
public function search($query, $filter = '', $start = 0, $limit = 10, $exact = 'false'){
if(!empty($query)){
$service_url = 'https://www.googleapis.com/freebase/v1/mqlread?query=';
$append = "[{\"id\":\"$query\",\"key\":[{\"namespace\":\"/wikipedia/en_title\",\"*\":null}]}]";
$url = $service_url. $append;
return json_decode(file_get_contents($url), true);
}
}
}
$freebase = new Freebase();
$result = $freebase->search('/m/03np_7');
$obj = json_encode($result);
echo $obj;
?>
My $obj output is as below.
{"result":[{"key":[{"namespace":"\/wikipedia\/en_title","value":"University_of_Texas_at_Arlington","type":"\/type\/key"}],"id":"\/m\/03np_7"}]}
I am trying to get the value field alone using php. I tried json_decode but it was saying it accepts only string and I have an array. How can I get the value alone from the Json_encode?