PHP pull value of Subkey from Array - php

I am currently using a third party API to find out the status of a game server. The API is via PHP and I am able to pull an Array with relevant information towards the servers status.
Here is my API's code:
#!/usr/bin/php -q
<?php
require('MulticraftAPI.php');
$api = new MulticraftAPI('http://ip.address.goes.here/multicraft/api.php', 'username', 'apikey');
$a = $api->getServerStatus($argv[1]);
print_r($a);
exit();
?>
This script is ran via PHP CLI: php status.php ${server_id} (19 in this case, but that is irrelevant)
The output is the following:
[admin#ns5001896 maps]# php status.php 19
Array
(
[success] => 1
[errors] => Array
(
)
[data] => Array
(
[status] => online
[onlinePlayers] => 0
[maxPlayers] => 32
)
)
My question:
How can I isolate the value of [status] in [data] and print it as the output. Just a single word "online" or "offline"
I have researched and any normal means from slice'ing the array to dumping vars doesn't work. I am kind of at my wits end here.
Thanks for your time!

Did you try this?:
echo $a['data']['status'];

Related

Parse Json Object PHP

I want to parse the following Json-Object:
{"multicast_id":123456,"success":0,"failure":1,"canonical_ids":0,"results":[{"error":"InvalidRegistration"}]}
I was able to succefully parse the values from success, failure, etc, but am having difficulties getting the "error"-msg ("InvalidRegistration").
I access them like this:
$b = json_decode($a, true);
if($b['success'] == 1){
$result = true;
}
How do i access the results / error section?
I tried to do it like this:
$b['results']['error']
but it didn't work.
Thank you for your help, in advance.
After you use json_decode function, a php array will be produced that will have the following structure:
Array
(
[multicast_id] => 123456
[success] => 0
[failure] => 1
[canonical_ids] => 0
[results] => Array
(
[0] => Array
(
[error] => InvalidRegistration
)
)
)
which means that in order to access the error key inside the results array you need to type $b['results'][0]['error']. Of course, this is not the optimal way unless you know that there is always going to be one index in the results array. In the case where an unknown number of indexes existed ([0], [1], [2] ... [n]), it would be a better idea to create a loop and go through each of them.

view query empty when only using 1 or 2 characters in couchDB/Php

Using the php couchbase sdk, and i've got a view which indexes various object types.
hitting the view directly returns results no problem
http://127.0.0.1:8092/default/_design/dev_domain/_view/search?stale=false&connection_timeout=60000&limit=10&skip=0&startkey=%22S%22&endkey=%22S\u02ad%22
Which returns happily
{"total_rows":700,"rows":[
{"id":"TestCompany\\Model\\SampleObject\\b63008d6d65df09a6947a9c3ebb9f3137ed3c54ac3754a21ba2098d80537c3ef","key":"sam","value":"SampleData"},
{"id":"TestCompany\\Model\\SampleObject\\f6b4119f7373edb6cfc7901702a2bb81b655834cd009cdfcaaafbaa1991f2cc4","key":"sam","value":"SampleData"},
{"id":"TestCompany\\Model\\SampleObject\\b63008d6d65df09a6947a9c3ebb9f3137ed3c54ac3754a21ba2098d80537c3ef","key":"samp","value":"SampleData"},
{"id":"TestCompany\\Model\\SampleObject\\f6b4119f7373edb6cfc7901702a2bb81b655834cd009cdfcaaafbaa1991f2cc4","key":"samp","value":"SampleData"},
{"id":"TestCompany\\Model\\SampleObject\\b63008d6d65df09a6947a9c3ebb9f3137ed3c54ac3754a21ba2098d80537c3ef","key":"sampl","value":"SampleData"},
{"id":"TestCompany\\Model\\SampleObject\\f6b4119f7373edb6cfc7901702a2bb81b655834cd009cdfcaaafbaa1991f2cc4","key":"sampl","value":"SampleData"},
{"id":"TestCompany\\Model\\SampleObject\\b63008d6d65df09a6947a9c3ebb9f3137ed3c54ac3754a21ba2098d80537c3ef","key":"sample","value":"SampleData"},
{"id":"TestCompany\\Model\\SampleObject\\f6b4119f7373edb6cfc7901702a2bb81b655834cd009cdfcaaafbaa1991f2cc4","key":"sample","value":"SampleData"},
{"id":"TestCompany\\Model\\SampleObject\\b63008d6d65df09a6947a9c3ebb9f3137ed3c54ac3754a21ba2098d80537c3ef","key":"sampled","value":"SampleData"},
{"id":"TestCompany\\Model\\SampleObject\\f6b4119f7373edb6cfc7901702a2bb81b655834cd009cdfcaaafbaa1991f2cc4","key":"sampled","value":"SampleData"}
]
}
But using the php sdk:
$test = $cb->view("dev_domain", "search",array("startkey"=>"s","endkey"=>"s"."\u02ad"));
return no results, using 3 or more keys is fine, ie:
$test = $cb->view("dev_domain", "search",array("startkey"=>"sam","endkey"=>"sam"."\u02ad"));
Array
(
[total_rows] => 700
[rows] => Array
(
[0] => Array
(
[id] => Authentic\Model\SampleObject\b63008d6d65df09a6947a9c3ebb9f3137ed3c54ac3754a21ba2098d80537c3ef
[key] => sam
[value] => SampleData
)
[1] => Array
(
[id] => Authentic\Model\SampleObject\f6b4119f7373edb6cfc7901702a2bb81b655834cd009cdfcaaafbaa1991f2cc4
[key] => sam
[value] => SampleData
)
)
)
I can't figure out how to pipe the sdk through charles (proxy) so not having any luck debugging that..
The problem here is that \u02ad is already JSON encoded, and so when you provide that to the CouchDB SDK in PHP it's going to get re-encoded (probably to \\u02ad which won't result in what you want by the time it gets to CouchDB itself).
You should either include the literal Unicode character in your string, or wrap your unicode string in a json_decode wrapper so that it's decoded before being passed into the SDK method, eg:
"endkey"=>"s".json_decode('"\u02ad"')
Note the single quotes around the double quoted sequence.
at the end of the day, of course my data was only indexed at 3 characters and over (as shown in the sample) , so my bad.

PHP - search for a key value and then find the value of another key in the same object subarray

I've searched a lot for this, and found several similar questions, but none quite address what I'm trying to accomplish.
I'm trying to write a code that will search a PHP (multi)multidimensional array to see which subarray contains the unique key value that I have. Then I would like it to return the value of a different key in that same object subarray.
$Arraytosearch = Array(
.
//various other subarrays
.
[fields] => Array (
.
.
.
//I don't know the number of the object subarray
[x] => PodioTextItemField Object (
[__attributes] => Array (
[field_id] => 37325091
[type] => text
[external_id] => id
[label] => ID
[values] => Array (
[0] => Array (
[value] => REF100019 ) )
[config] => Array (
[description] => [settings] => Array (
[size] => small )
[required] => [mapping] => [label] => ID [visible] => 1 [delta] => 2 ) )
.
.
.
//(and so on)
I'd like to write a function that will return "REF100019" by supplying the value of the field_id => 37325091.
Some things I have tried that I couldn't get to work:
foreach
and new RecursiveIterator although the tutorials I read weren't useful for my case here.
Even though the array looks complicated, I think it will be easy since I already have the field id of the parent array.
Thank you in advance for any guidance or sample codes that will work!
Background: This is a part of the response I get from Podio after submitting a request to their API. I just don't know how to take that response and get the piece I need (the ID) so that I can echo it for users).
EDIT: Thank you Orangepill and Barmar for the support. I tried your code. But was getting an error, which made me realize I hadn't given you the full array. I figured out how to get the Podio response to display in a more readable format (I was reading the full JSON response before from the Podio debug file which was super confusing), and figured out the full array is actually structured as I have shown below.
I then took your code and was able to figure out how to make it work for my scenario (see below). Very proud of myself considering I have never written any code before, but I couldn't have done it without your help! Thanks again!
$Arraytosearch = Array(
[items] => Array(
[0] => PodioItem Object(
[_attributes] => Array(
[fields] => Array (
[x] => PodioTextItemField Object (
[__attributes] => Array(
[field_id] => 37325091
[values] => Array(
[0] => Array(
[value] => REF100019 ) )
Note: For anyone who is new to programming like myself and wants the Podio response (or any JSON string) to display in a "pretty" readable format like above, use the code (from Display an array in a readable/hierarchical format thanks to Phenex):
print "<pre>";
print_r($Arraytoformat);
print "</pre>";
And finally, the full code I used (using Orangepill's answer below) which searches the objects and arrays and gives me what I have been searching for for days now is as follows:
$Arraytosearch = PodioItem::filter(APP_ID, $filterParams);
$fieldID = 37325091;
function getFirstValueByFieldId($fieldId, $Arraytosearch){
foreach($Arraytosearch["items"][0]->__attributes["fields"] as $textitem){
if ($textitem->__attributes["field_id"] == $fieldId){
return $textitem->__attributes["values"][0]["value"];
}}}
$refID = getFirstValueByFieldId($fieldID, $Arraytosearch);
The podio-php library has built-in methods that handle all this for you. There's no need to mess with the __attributes property yourself.
You can see a bunch of examples at https://github.com/podio/podio-php/blob/master/examples/items.php
In your case:
// Get item collection
$itemCollection = PodioItem::filter(APP_ID, $filterParams);
$fieldID = 37325091;
foreach ($itemCollection['items'] as $item) {
// Get the field from the item
$field = $item->field($fieldID);
// Now you can print the value of that field
print $field->humanized_value;
// Or if you don't want to have the content sanitized:
print $field->values[0]['value'];
}
There is a lot of ways to skin this cat... this is probably the most straight forward
function getFirstValueByFieldId($fieldId, $Arraytosearch){
foreach($Arraytosearch["fields"] as $textitem){
if ($textitem->__attributes["field_id"] == $fieldId){
return $textitems->__attributes["values"][0]["value"];
}
}
}
to Use in your case would be
echo getFirstValueByFieldId("37325091", $Arraytosearch);
Basically it walks the elements in the fields array and returns the value in the first associated value in the values array where field_id is equal to the parameter of the function.

Extract values from php array [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Able to see a variable in print_r()'s output, but not sure how to access it in code
I am using SOAP to get data from the server and in response i am getting a php array like this
Array
(
[BookResult] => stdClass Object
(
[PNR] => 5WPODU
[BookingId] => 31149
[Status] => stdClass Object
(
[StatusCode] => 03
[Description] => Fare is not available at the time of booking
[Category] => BK
)
[SSRDenied] => N
[ProdType] => Flight
)
)
All i want to know is how can i extract "PNR" and "StatusCode" value in separate variables so that i can store them in database.
Tried this not working
$p = (object) $array;
echo $p->StatusCode;
Try this:
$PNR = $array["BookResult"]->PNR;
$StatusCode= $array["BookResult"]->Status->StatusCode;
$array is an array. So first dive is $array['BookResult'].
BookResult is stdClass instance so next goes $array['BookResult']->Status (get object's property).
Status is also stdClass instance so get it's property: $array['BookResult']->Status->StatusCode
var_dump($array['BookResult']->PNR);
var_dump($array['BookResult']->Status->StatusCode);
Assuming results are being stored in $array
echo $array['BookResult']->Status->StatusCode;
echo $array['BookResult']->PNR;

Using abraham's twitteroauth: The "followers/ids" next_cursor is always 0

twitteroauth has been fantastic up until now, but I'm having trouble gathering all of the followers of certain users.
For example:
$method = 'followers/ids';
$params = array("screen_name"=>"governoromalley","cursor"=>"-1");
print_r($conn->get($method));
Returns / Prints the object claiming that there is only a 0 for next_cursor:
stdClass Object ( [previous_cursor_str] => 0 [next_cursor] => 0 [ids] =>
Array ( [0] => 353642204 [1] => 98012791 [2] => 72607824 [3] =>...
But, when curling via the http://dev.twitter.com OAuth tool, I get something showing that the next_cursor is there, but I can't seem to get it via the PHP SDK.
{"previous_cursor_str":"0","next_cursor":1380213447767347311,"ids":
[23639237,324619439,282668815,...
How can I solve this conundrum? I'm willing to do any silly hacks as necessary.
Thanks for any help!
Ended up figuring it out.
Seems like twitteroauth sdk wants user_ids instead:
//Where GovernorOMalley's user_id = 15824288
$method = 'followers/ids/15824288';
print_r($conn->get($method));
Gives the proper cursor elements.

Categories