Parsing object with arrays in PHP - php

I'm using Google's Natural Language API and it's working fine and returning data. I'm just not able to parse it correctly. I'd like to form a JSON object I can then use with AJAX or similar. What I need out of this are mainly the sentences and their sentiment. I'm struggling with this object that I get back:
object(Google\Cloud\NaturalLanguage\Annotation)#21 (1) {
["info":"Google\Cloud\NaturalLanguage\Annotation":private]=>
array(3) {
["documentSentiment"]=>
array(2) {
["magnitude"]=>
float(1.4)
["score"]=>
int(0)
}
["language"]=>
string(2) "en"
["sentences"]=>
array(2) {
[0]=>
array(2) {
["text"]=>
array(2) {
["content"]=>
string(19) "I love everything!\"
["beginOffset"]=>
int(0)
}
["sentiment"]=>
array(2) {
["magnitude"]=>
float(0.8)
["score"]=>
float(0.8)
}
}
[1]=>
array(2) {
["text"]=>
array(2) {
["content"]=>
string(18) "I hate everything!"
["beginOffset"]=>
int(21)
}
["sentiment"]=>
array(2) {
["magnitude"]=>
float(0.6)
["score"]=>
float(-0.6)
}
}
}
}
}
ADDED:
The very last bit of my PHP code is:
$annotation = $language->analyzeSentiment($text);
$sentiment = $annotation->sentiment();
echo 'Text: ' . $text . '
Sentiment: ' . $sentiment['score'] . ', ' . $sentiment['magnitude'];
return $sentiment;
This successfully returns the score and magnitude for the overall "document" as shown in the part of the array under "documentSentiment". What I need (in addition to this), is the data under sentences. In particular, content, magnitude and score.

Since $sentiment['sentences'] is an array -
["sentences"]=>
array(2) {
...
}
you need to loop over the values, with foreach() for example -
....
echo 'Text: ' . $text . '
Sentiment: ' . $sentiment['score'] . ', ' . $sentiment['magnitude'];
foreach($sentiment['sentences'] as $sentence){
echo 'Text: ' .$sentence["text"]["content"] . '
Sentiment: ' . $sentence["sentiment"]["score"] . ', ' . $sentence["sentiment"]["magnitude"];
}

Related

Matching array key and value and displaying only those in the matched result

I am working with an API which provides a result set in JSON, I transform that data into a PHP array to work with it on my interface.
The issue i'm having now is trying to filter the data based on a particular key having a certain value.
Here is the result set returned:
[
{
"id":5,
"firstname":"Joel ",
"lastname":"Abase",
"displayName":"Abase, Joel ",
"officeId":3,
"officeName":"Birmingham",
"isLoanOfficer":true,
"isActive":true
},
{
"id":1,
"firstname":"Precious ",
"lastname":"Love",
"displayName":"Love, Precious ",
"officeId":4,
"officeName":"Manchester",
"isLoanOfficer":true,
"isActive":true
},
{
"id":2,
"firstname":"Bernard ",
"lastname":"Aikins",
"displayName":"Aikins, Bernice ",
"officeId":2,
"officeName":"Manchester",
"isLoanOfficer":false,
"isActive":true
},
{
"id":8,
"firstname":"Kwame",
"lastname":"Joseph",
"displayName":"Joseph, Kwame",
"officeId":2,
"officeName":"Manchester",
"isLoanOfficer":true,
"isActive":true,
"joiningDate":[
2018,
5,
1
]
},
{
"id":4,
"firstname":"Janine ",
"lastname":"Hayden",
"displayName":"Hayden, Janine ",
"officeId":1,
"officeName":"Head Office",
"isLoanOfficer":false,
"isActive":true
},
{
"id":6,
"firstname":"Esther",
"lastname":"Monroe",
"displayName":"Monroe, Esther",
"officeId":2,
"officeName":"London",
"isLoanOfficer":true,
"isActive":true,
"joiningDate":[
2017,
11,
1
]
}
]
I would like to filter the results in a loop where the 'isLoanOfficer' is equal to true, essentially only showing those who are loan officers.
Here is what I have tried so far:
<div class="col-sm-5">
<label class="control-label" for="staffId">Loan Officer<span style="color:red;">*</span></label>
<?php
$s = 0;
$temp_staff = json_decode($staff_json, true);
$count_staff = count($temp_staff);
echo '<select class="form-control" type="text" name="staffId" required>';
echo "<option value=". ">" . " </option>";
while($s < $count_staff && $temp_staff[$s]['isLoanOfficer'] == true){
echo "<option value=" . $temp_staff[$s]['id'] . ">" . $temp_staff[$s]['displayName'] . " </option>";
$s++;
}
echo '</select>';
?>
<br>
</div>
I also tried adding this code inside the while loop:
if($temp_staff[$s]['isLoanOfficer'] == true) {
echo "<option value=" . $temp_staff[$s]['id'] . ">" . $temp_staff[$s]['displayName'] . " </option>";
$s++;
}
It seems that it only evaluates the first value and then exits. Any help?
You'll have to use the condition inside the loop. Try the below code :
while($s < $count_staff){
if ($temp_staff[$s]['isLoanOfficer'] == true) {
echo "<option value=" . $temp_staff[$s]['id'] . ">" . $temp_staff[$s]['displayName'] . " </option>";
}
$s++;
}
Due to that condition your $s++ is not being executed properly.
Hope this helps.
You do not need to loop.
You can use array_intersect, array_intersect_key and array_column to find the true values.
First filter out the loanofficer column and use array_intersect to only get the true values.
Now we have an array with true values and it's corresponding key.
Use array_intersect_key to match it with the original array and the return is your filtered array.
$arr = json_decode($str, true);
$loan = array_intersect(array_column($arr, "isLoanOfficer"), [true]);
var_dump(array_intersect_key($arr, $loan));
From here is't a simple foreach outputing every value or use implode to build the output string.
https://3v4l.org/eh4uD
Output:
array(4) {
[0]=>
array(8) {
["id"]=>
int(5)
["firstname"]=>
string(5) "Joel "
["lastname"]=>
string(5) "Abase"
["displayName"]=>
string(12) "Abase, Joel "
["officeId"]=>
int(3)
["officeName"]=>
string(10) "Birmingham"
["isLoanOfficer"]=>
bool(true)
["isActive"]=>
bool(true)
}
[1]=>
array(8) {
["id"]=>
int(1)
["firstname"]=>
string(9) "Precious "
["lastname"]=>
string(4) "Love"
["displayName"]=>
string(15) "Love, Precious "
["officeId"]=>
int(4)
["officeName"]=>
string(10) "Manchester"
["isLoanOfficer"]=>
bool(true)
["isActive"]=>
bool(true)
}
[3]=>
array(9) {
["id"]=>
int(8)
["firstname"]=>
string(5) "Kwame"
["lastname"]=>
string(6) "Joseph"
["displayName"]=>
string(13) "Joseph, Kwame"
["officeId"]=>
int(2)
["officeName"]=>
string(10) "Manchester"
["isLoanOfficer"]=>
bool(true)
["isActive"]=>
bool(true)
["joiningDate"]=>
array(3) {
[0]=>
int(2018)
[1]=>
int(5)
[2]=>
int(1)
}
}
[5]=>
array(9) {
["id"]=>
int(6)
["firstname"]=>
string(6) "Esther"
["lastname"]=>
string(6) "Monroe"
["displayName"]=>
string(14) "Monroe, Esther"
["officeId"]=>
int(2)
["officeName"]=>
string(6) "London"
["isLoanOfficer"]=>
bool(true)
["isActive"]=>
bool(true)
["joiningDate"]=>
array(3) {
[0]=>
int(2017)
[1]=>
int(11)
[2]=>
int(1)
}
}
}
If you want to keep the arrays which only have "isLoanOfficer":true you could use array_filter:
$temp_staff = array_filter($temp_staff, function($x){
return $x["isLoanOfficer"] === true;
}
);
Demo
The easiest and most readable way, using a foreach:
$temp_staff = json_decode($staff_json, true);
foreach($temp_staff as $member) {
if($member['isLoanOfficer']) {
echo '<option value="' . $member['id'] . '">' . $member['displayName'] . '</option>';
}
}

Echo status message in php geonames timezone

I'm using following code php to get timezone:
$url = 'http://api.geonames.org/timezone?lat=' . $latitude . '&lng=' . $longitude . '&username=demo';
$xml = simplexml_load_file($url);
foreach($xml->children() as $timezone)
{
echo "TimezoneId: ".$timezone->timezoneId." ";
echo "DstOffset : ".$timezone->dstOffset." ";
echo "GmtOffset : ".$timezone->gmtOffset." ";
}
it work but for latitude and longitude of Antartica for example it give error status message:
<status message="no timezone information found for lat/lng" value="15"/>
How to echo this message?
I'm tryng this:
if ($xml->status) {
echo "error: ".$timezone->status['message']. "";
}
but don't work
You are trying to get an element from object, which doesn't exist. In such a XML element you have attributes and some values like in your case: countryCode, countryName, dstOffset, gmtOffset and etc. If you use var_dump() the result you can see the error message is in these attributes, which is an array.
Here you are an example:
var_dump() on a location without problem:
object(SimpleXMLElement)#4 (12) {
["#attributes"]=>
array(1) {
["tzversion"]=>
string(11) "tzdata2014i"
}
["countryCode"]=>
string(2) "KG"
["countryName"]=>
string(10) "Kyrgyzstan"
["lat"]=>
string(7) "40.4246"
["lng"]=>
string(7) "74.0021"
["timezoneId"]=>
string(12) "Asia/Bishkek"
["dstOffset"]=>
string(3) "6.0"
["gmtOffset"]=>
string(3) "6.0"
["rawOffset"]=>
string(3) "6.0"
["time"]=>
string(16) "2015-07-09 19:53"
["sunrise"]=>
string(16) "2015-07-09 05:41"
["sunset"]=>
string(16) "2015-07-09 20:36"
}
And here a var_dump() of Antartica:
object(SimpleXMLElement)#4 (1) {
["#attributes"]=>
array(2) {
["message"]=>
string(41) "no timezone information found for lat/lng"
["value"]=>
string(2) "15"
}
}
You can easily handle and print this error message like that:
if ($xml->status) {
echo 'error:' . $timezone->attributes()->message;
}
try this,
<?php
$url = 'http://api.geonames.org/timezone?lat=' . $latitude . '&lng=' . $longitude . '&username=demo';
$xml = simplexml_load_file($url);
foreach ($xml->geoname as $o_location){
printf(
'Name %s<br>
lat is %s<br>
lon is %s<br>
geonameId is %s<br>
countryCode is %s<br>
countryName is %s<br>
fcl is %s<br>
fcode is %<br>
',
$o_location->name,
$o_location->lat,
$o_location->lng,
$o_location->geonameId,
$o_location->countryCode,
$o_location->countryName,
$o_location->fcl,
$o_location->fcode
);
}
?>

Array instead of Array Element

I'm trying to turn Minecraft names into UUIDs, which can be converted into a "name history". I have the name->UUID part down pat, but the name history is getting an error.
Running this code, the $uuid variable contains an array of all the UUIDs I'm trying to convert into a name history - I then try to run all of them through the API, and depending on how many past names the user has, add » icons to signify a change. Unfortunately, with test data of something like this:
Foo
Bar (changed to Baz)
it outputs
Array | Array » Array |
, not the
Foo | Bar » Baz |
it's supposed to. I know I'm probably getting the array as an object, but I don't know where I would be doing that or how to get the element instead.
(and here's the code)
$uuid_real = json_decode($uuid, TRUE);
foreach($uuid_real as $uuid_totest){
$toadd = json_decode(file_get_contents('https://api.mojang.com/user/profiles/' . $uuid_totest['id'] . '/names'), TRUE);
if(count($toadd)==1){
$results .= $toadd['0'] . " | ";
}elseif(count($toadd)==2){
$results .= $toadd['0'] . " » " . $toadd['1'] . " | ";
}elseif(count($toadd)==3){
$results .= $toadd['0'] . " » " . $toadd['1'] . " » " . $toadd['2'] . " | ";
}
Here is var_dump for $toadd with some currently online users:
array(1) {
[0]=>
array(1) {
["name"]=>
string(10) "lottie1664"
}
}
array(1) {
[0]=>
array(1) {
["name"]=>
string(12) "wingmanfoutz"
}
}
array(1) {
[0]=>
array(1) {
["name"]=>
string(11) "bigfoot2991"
}
}
array(1) {
[0]=>
array(1) {
["name"]=>
string(13) "mrstampycat05"
}
}
array(1) {
[0]=>
array(1) {
["name"]=>
string(10) "MEHLAWLARZ"
}
}
array(1) {
[0]=>
array(1) {
["name"]=>
string(10) "metboy2002"
}
}
array(1) {
[0]=>
array(1) {
["name"]=>
string(10) "SILVERMAN2"
}
}
array(2) {
[0]=>
array(1) {
["name"]=>
string(11) "salesman200"
}
[1]=>
array(2) {
["name"]=>
string(8) "Quartzic"
["changedToAt"]=>
int(1423055736000)
}
}
array(1) {
[0]=>
array(1) {
["name"]=>
string(13) "MercenaryCrow"
}
}
array(1) {
[0]=>
array(1) {
["name"]=>
string(8) "fishmeal"
}
}
It is because $toadd[0] $toadd[1] and $toadd[2] are arrays not strings, please provide here var_dump($toadd) and we can help you
EDIT:
So as you can see there is no string under $toadd[x] but an array looking like this :
array(1) {
["name"]=>
string(10) "lottie1664"
}
so modify your code and use :
$toadd[0]['name']
$toadd[1]['name']
$toadd[2]['name']

How to interpret this json decoded array?

How can I interpret this JSON decoded array? It seems like more of a complex array than I'm accustomed to dealing with so any help would be appreciated.
Thanks.
array(1){
[0]=> object(stdClass)#1 (11){
["id"]=> string(5) "72324"
["txid"]=> string(64) "**bitcoin_tx_id**"
["from"]=> string(34) "**bitcoin_address**"
["to"]=> string(20) "email#somewhere.com"
["amount"]=> int(10000000)
["amount_sent"]=> int(0)
["note"]=> string(0) ""
["time"]=> float(1379742767000)
["to_addr"]=> string(34) "**bitcoin_address**"
["read"]=> string(1) "1"
["balance"]=> string(10) "0.10000000"
}
}
It is returning an array of objects, it looks like you're just dumping it to stdout. Toss the output from json_decode() inside a variable and you may access it like this:
$decoded = json_decode($data);
foreach($decoded as $obj) {
echo "ID: " . $obj->id . ', ';
echo "TXID: " . $obj->txid . ', ';
echo "From: " . $obj->from . ', ';
echo "To: " . $obj->to. ', ';
// ...
echo "<br>";
}
If you want json_decode() to return an associative array (which most people are used to), simply set the second parameter to true.

PHP Echo array values loop (no data displayed)

I have an array ... Here is the structure / data:
array(1) {
[0]=> object(SimpleXMLElement)#1 (18)
{
["data_123"]=> object(SimpleXMLElement)#3 (29)
{
["field1"]=> string(7) "123"
["field2"]=> string(2) "10"
["field3"]=> string(19) "2013-03-05 17:00:00"
["field4"]=> string(19) "2013-03-05 18:00:00"
}
["data_234"]=> object(SimpleXMLElement)#4 (29)
{
["field1"]=> string(7) "234"
["field2"]=> string(2) "10"
["field3"]=> string(19) "2013-03-05 17:40:00"
["field4"]=> string(19) "2013-03-05 18:10:00"
}
}
}
I am trying to create a loop to display the data but nothing is showing up:
foreach ($result as $key => $list) {
echo "key.: " . $key . "\n";
echo "field1: " . $list['field1'] . "\n";
echo "field2: " . $list['field2'] . "\n";
}
It's just not returning any data.
I'm guessing that the loop might be wrong for this array structure?
How can I get the data echoed for this array?
$list is an array of objects so you need two loops and appropriate syntax. e.g.:
foreach($list as $objects) {
foreach($objects as $key => $obj) {
echo "key.: " . $key . "\n";
echo $obj->field1 . "\n";
echo $obj->field2 . "\n";
echo $obj->field3 . "\n";
echo $obj->field4 . "\n";
}
}

Categories