PHP Echo array values loop (no data displayed) - php

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";
}
}

Related

Find duplicate elements in an array

I got an array of coins with many details, that looks partially like that:
array(360) {
["VEN/USDT"]=>
array(15) {
["tierBased"]=>
bool(false)
}
["id"]=>
string(7) "VENUSDT"
["symbol"]=>
string(8) "VEN/USDT"
["base"]=>
string(3) "VEN"
["quote"]=>
string(4) "USDT"
["lot"]=>
float(0.01)
["active"]=>
bool(true)
}
All I need is this part:
["id"]=>
string(7) "VENUSDT"
["symbol"]=>
string(8) "VEN/USDT"
["base"]=>
string(3) "VEN"
["quote"]=>
string(4) "USDT"
if "base" is more often than once in the entire array.
The final code was:
$base_array = array();
foreach ($markets as $key=>$value) {
echo "1. Key = " . $key . "\n";
foreach ($value as $key => $value) {
if ($key == "base") {
echo "Base = " . $value . "\n";
array_push($base_array, $value);
}
}
}
// Duplicates we need only!
$unique = array_unique($base_array);
$duplicates1 = array_diff_assoc($base_array, $unique);
$duplicates = array_unique($duplicates1);
var_dump($duplicates);

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>';
}
}

Parsing object with arrays in 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"];
}

PHP JSON Array Loop

array(1) {
["value"] => array(1000) {
[0]=> array(9) {
["PartitionKey"]=> string(11)"AWT-GPI.com"
["RowKey"]=> string(36) "0024a6ac-6cf1-454a-91b2-15bfec3a3d86"
["Timestamp"]=> string(28) "2016-09-09T20:16:26.8674483Z"
["Email"]=> string(20) "ginyoung30#gmail.com"
["First_Name"]=> string(8) "Jennifer"
["Hash"]=> string(32) "d656d0c21b8f3c14fe03232bb68d1b53"
["IP_1"]=> string(0) ""
["Last_Name"]=> string(5) "Young"
["Username"]=> string(9) "flacobell"
}
[1]=> array(9) {
["PartitionKey"]=> string(11) "AWT-GPI.com"
["RowKey"]=> string(36) "002c00c4-e064-43e8-9dd8-319c8d6663bd"
["Timestamp"]=> string(28) "2016-09-09T20:19:54.5500874Z"
["Email"]=> string(22) "Glenn#flavorleague.com"
["First_Name"]=> string(1) "G"
["Hash"]=> string(32) "1444a7b2c86506158013d1175137eede"
["IP_1"]=> string(0) "" ["Last_Name"]=> string(6) "Wilson"
["Username"]=> string(13) "misterspeed76"
}
}
}
This is what I get when I call my API, now this is just one sample. If you see there is [0] which indicates entry 1 and than [1] which indicates entry two. There are more but I have shortened it. Right now I can do this
foreach ($null_check['value'] as $key => $data) {
// Get rid of '_' in Website Names
$new = str_replace('_', ' ', $data['PartitionKey']);
echo 'Website: '.$new.'<br>';
echo 'Email: '.$data['Email'].'<br>';
}
Which allows me to get ALL of the Email and such
But what I want is to be able to take [0] and format that so doing a loop. It has something to do with i++ but I don't really understand it.
Here is what I really want:
PartitionKey: AWT-GPI.com
Email: ginyoung30#gmail.com
First Name: Jennifer
Last Name: Young
Hash: d656d0c21b8f3c14fe03232bb68d1b53
As you can see I've taken out some of the things and rearranged it. I was wondering if this is possible by using foreach. However, each entry might be different, so [1] might not have 'email' or 'first_name'
Thank you in advanced.
Update:
After some coding I got until here
$count = count($null_check);
for ($i = 0; $data < $count; $i++) {
foreach ($null_check['value'][$i] as $key => $data) {
$parsed_key = str_replace('_', ' ', $key);
echo $parsed_key.': '.$data.'<br>';
}
echo '<br><br>';
}
This allows me to just echo all the details but I have no idea which data is which and how to organize it.
Output:
PartitionKey: AWT-GPI.com
RowKey: 0024a6ac-6cf1-454a-91b2-15bfec3a3d86
Timestamp: 2016-09-09T20:16:26.8674483Z
Email: ginyoung30#gmail.com
First Name: Jennifer
Hash: d656d0c21b8f3c14fe03232bb68d1b53
IP 1:
Last Name: Young
Username: flacobell
PartitionKey: AWT-GPI.com
RowKey: 002c00c4-e064-43e8-9dd8-319c8d6663bd
Timestamp: 2016-09-09T20:19:54.5500874Z
Email: Glenn#flavorleague.com
First Name: G
Hash: 1444a7b2c86506158013d1175137eede
IP 1:
Last Name: Wilson
Username: misterspeed76
See if this helps:
foreach($jsonArray as $jsonObj)
{
foreach($jsonObj as $key => $value)
{
if ($key === "PartitionKey" ||
$key === "Email" ||
$key === "First_Name" ||
$key === "Last_Name" ||
$key === "Hash") {
echo $key . ": " . $value . "<br>";
}
}
}
Assuming you have json_decode($json) of JSON array of objects.
foreach ($null_check['value'] as $key => $data) {
if(isset($data['PartitionKey'])){
$parsed_website = str_replace('_', ' ', $data['PartitionKey']);
echo 'Website: '.$parsed_website.'<br>';
}
if(isset($data['Username'])){
echo 'Username: '.$data['Username'].'<br>';
}
if(isset($data['Email'])){
echo 'Email: '.$data['Email'].'<br>';
}
if(isset($data['Hash'])){
echo 'Hash: '.$data['Hash'].'<br>';
}
if(isset($data['Salt'])){
echo 'Salt: '.$data['Salt'].'<br>';
}
if(isset($data['First_name'])){
echo 'First Name: '.$data['First_Name'].'<br>';
}
if(isset($data['Last_Name'])){
echo 'Last Name: '.$data['Last_Name'].'<br>';
}
if(isset($data['IP_1'])){
$null_ip = array('0000-00-00', null);
if(!in_array($data['IP_1'], $null_ip)) {
echo 'Registered IP: '.$data['IP_1'].'<br>';
}
}
echo '<br><br>';
}
I just did a isset to chcek if there was a key. This will go through all the array. Thank you for helping but this worked for me.

How to use foreach() to display results from array

I have the following query:
$sth = $this->db->prepare("SELECT * FROM comment WHERE status = 1");
$sth->setFetchMode(PDO::FETCH_ASSOC);
$sth->execute();
$reviews = array();
while($row = $sth->fetch()){
$reviews[]['name'] = $row['name'];
$reviews[]['comment'] = $row['comment'];
$reviews[]['star'] = $row['star'];
}
return $reviews;
}
Which returns the following for var_dump($this->reviews):
array(9) {
[0]=> array(1) { ["name"]=> string(5) "name1" }
[1]=> array(1) { ["comment"]=> string(8) "comment1" }
[2]=> array(1) { ["star"]=> string(1) "4" }
[3]=> array(1) { ["name"]=> string(5) "name2" }
[4]=> array(1) { ["comment"]=> string(8) "comment2" }
[5]=> array(1) { ["star"]=> string(1) "4" }
[6]=> array(1) { ["name"]=> string(5) "name3" }
[7]=> array(1) { ["comment"]=> string(8) "comment3" }
[8]=> array(1) { ["star"]=> string(1) "4" }
}
How can I use foreach to display name, comment, star by row?
I.e.:
name1, email1#email.com, comment1
name2, email2#email.com, comment2
name3, email3#email.com, comment3
I know it should be something like:
foreach( $this->reviews as $key){
echo "Name:". $this->reviews['name'] . "Email:" . $this->reviews['email'] . "Comment:" . $this->reviews['comment'];
}
But this gives me Notice: Undefined index: name. How do I define the index?
You are setting up the insert into the array incorrectly:
while($row = $sth->fetch()){
$reviews[]['name'] = $row['name'];
$reviews[]['comment'] = $row['comment'];
$reviews[]['star'] = $row['star'];
}
The shorthand [] inserts a new element each and every single time, you want to actually insert an array AS the element.
while($row = $sth->fetch()){
$revArr=array('name' => $row['name'], 'comment' => $row['comment'], 'star' => $row['star']);
$reviews[]=$revArr;
}
Edit: Now change your second foreach to this:
foreach( $this->reviews as $key){
echo "Name:". $key['name'] . "Email:" . $key['email'] . "Comment:" . $key['comment'];
}
You need to generate an array of arrays. Something like
while($row = $sth->fetch()){
$reviews[] = array('name' => $row['name'], 'comment' => $row['comment'], 'star'=> $row['star']);
}
Now your $reviews object will have just as many elements as there were rows in the query result, and you can print it any way you want.
As for printing (which I think is where your error message is coming from):
foreach($reviews as $thisValue) {
echo "Name: ". $value['name'];
}
should work.
You should use your foreach loop like this:
foreach( $this->reviews as $value){
echo "Name:". $value['name'] . "Email:" . $value['email'] . "Comment:" . $value['comment'];
}
Notice how i use $value instead of $this->reviews inside the loop.
foreach( $this->reviews as $key){
echo "Name:". $this->reviews['name'] . "Email:" . $this->reviews['email'] . "Comment:" . $this->reviews['comment'];
}
this is not the right way, because now you are working on $key so write -
foreach( $this->reviews as $key){
echo "Name:". $key['name'] . "Email:" . $key['email'] . "Comment:" . $key['comment'];
}
you can do it as follow:
$reviews = array();
while($row = $sth->fetch()){
$reviews[] = array($row['name'], $row['comment'], $row['email'], $row['star']);
}
and then you can do a heredoc:
$str = '';
foreach( $this->reviews as $review ){
$str .=<<<html
name: {$review['name']}
email: {$review['email']}
comment: {$review['comment']}
start: {$review['star']}
html;
}
finally i echo everything:
echo $str;
I think this is much cleaner, and you can add any html.

Categories