How to use foreach() to display results from array - php

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.

Related

PHP variables, what is wrong with my code?

There is a PHP script that get's new data using python script.
I'm able to foreach and loop and get key2, and value2 for array but unable to get $address and $product variables to put it into $shell command. What is wrong with my variables?
Just starting to code, it would be helpful if anyone teaches me this.
foreach ($gotdata as $key1 => $value1) {
foreach ($value1 as $key2 => $value2) {
//print " key2: " . $key2 . " value2: ". $value2;
$address = "";
$maker = "";
if($key2 == 'Address'){
$address = $value2;
print "address: ".$address; //able to get it on console
}
if($key2 == 'Product'){
$product = $value2;
print "product: ".$product; //able to get it on console
}
$shell = 'python /opt/getdata.py '.$address.' '.$product;
print "shell:" . $shell; //not able to get $address and $product
// $current = shell_exec($shell);
// $current = (int)$current;
// print "current:" . $current;
}
}
This is what the multidimensional array looks like.
The main array is different size every time I run the script. It could be 10 or 14 etc.
The
subarrays on the other hand always have the same six items.
array(2) {
[0]=>
array(6) {
["Id"]=>
string(1) "1"
["Name"]=>
string(15) "name01"
["Address"]=>
string(12) "1.1.1.1"
["Product"]=>
string(1) "1"
["Current"]=>
string(3) "111"
["DateTime"]=>
string(19) "2020-09-09 15:03:46"
}
[1]=>
array(6) {
["Id"]=>
string(1) "2"
["Name"]=>
string(15) "name02"
["Address"]=>
string(12) "1.1.1.2"
["Product"]=>
string(1) "1"
["Current"]=>
string(3) "111"
["DateTime"]=>
string(19) "2020-09-09 15:03:46"
}
I assume you can access the values you want directly from the main loop.
EDIT: Now that the array has been posted, I'm sure this will work.
No need to nest loop the array
foreach ($gotdata as $key1 => $value1) {
$shell = 'python /opt/getdata.py '.$value1['Address'] . ' ' . $value1['Product'];
print "shell:" . $shell; //not able to get $address and $product
}
Nesting a foreach loop is the same as accessing the subarray item.
i do not know what is your desire output. But if you want both values. Try it
foreach ($gotdata as $key1 => $value1) {
$address = "";
$product = "";
foreach ($value1 as $key2 => $value2) {
//print " key2: " . $key2 . " value2: ". $value2;
if($key2 == 'Address'){
$address = $value2;
print "address: ".$address; //able to get it on console
}
elseif($key2 == 'Product'){
$product = $value2;
print "product: ".$product; //able to get it on console
}
if($address!="" && $product!=""){
$shell = 'python /opt/getdata.py '.$address.' '.$product;
print "shell:" . $shell; //not able to get $address and $product
}
// $current = shell_exec($shell);
// $current = (int)$current;
// print "current:" . $current;
}
}
Also you have not define $product in your code.

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);

How to access array elements

I am getting this as var_dump:
array(1) {
[0]=>
array(4) {
["num"]=>
string(1) "1"
["yyyy"]=>
string(4) "2013"
["mm"]=>
string(2) "12"
["dd"]=>
string(2) "11"
}
}
How to access the array elements?
Let's assume your array is $arr, you can do
echo $arr[0]['num'];
echo $arr[0]['yyyy'];
echo $arr[0]['mm'];
echo $arr[0]['dd'];
As you are fetching from a database, you will receive an array for each result row, and within each array will be another array of columns. you can use a foreach() loop to iterate over the data, as follows:
foreach($arr as $row) {
echo $row['num'] . ':' . $row['yyyy'] . '-' . $row['mm'] . '-' . $row['dd'] . "\n";
}
try this
foreach($array as $value) {
foreach($value as $k=>$v) {
echo $k . " : " . $v .'<br/>';
}
echo '<hr>';
}
Please have a look at the official PHP Doc article about arrays.
In your case:
$yourArrayVariable[0]['yyyy']
Will let you access the element with value 2013.
Or if you have an undefined number of array entries you can iterate over it with either foreach or for.
foreach($yourArrayVariable as $key => $value) {
echo $key , ': ' , $value , '<br>';
}
or if you have only numeric indeces without a gap:
$arrCount = count($yourArrayVariable);
for($i = 0; $i < $arrCount; ++$i) {
echo $i , ': ' , $arrCount[0] , '<br>';
}
store array in a variable like
$arr =array(1) {
[0]=>
array(4) {
["num"]=>
string(1) "1"
["yyyy"]=>
string(4) "2013"
["mm"]=>
string(2) "12"
["dd"]=>
string(2) "11"
}
}
for access array elements you have to use following code
echo $arr[0]['num'];
echo $arr[0]['yyyy'];
echo $arr[0]['mm'];
echo $arr[0]['dd'];o $arr[0]['num']
$arr =Array(
0=>array(
"num"=>"1",
"yyyy"=>"2013",
"mm"=>"12",
"dd"=>"11",
)
);
foreach ($arr as $value) {
echo "num: ".$value["num"];
echo "yyyy: ".$value["yyyy"];
echo "mm: ".$value["mm"];
echo "dd: ".$value["dd"];
}
You can get the value using echo $array[0]['num']; gives output as 1
$array ='your array data here';
foreach($array as $key=>$value) {
echo "num: ". $value['num'] . "/yyyy: ". $value['yyyy']. " /mm: ". $value['mm'] . " /dd: ". $value['dd'] . "<br>";
}

create php array using simpleXMLobject

I'm trying to get this array ($resdata) with object(SimpleXMLElement) into a php array:
$resdata =
array(59) {
[0]=> ...
[10]=> object(SimpleXMLElement)#294 (28) {
["reservation_id"]=> string(7) "8210614"
["event_id"]=> string(6) "279215"
["space_reservation"]=> array(2) {
[0]=> object(SimpleXMLElement)#344 (9) {
["space_id"]=> string(4) "3760"
["space_name"]=> string(9) "205"
["formal_name"]=> string(33) "Center" }
[1]=> object(SimpleXMLElement)#350 (9) {
["space_id"]=> string(4) "3769"
["space_name"]=> string(9) "207"
["formal_name"]=> string(32) "Right" } } }
}
I've tried:
$res = (array)$resdata;
$reservation = $res['reservation'];
$result = array();
foreach ($reservation as $key => $value){
$res = array($value);
$spid = $res[0]->space_reservation->space_id;
echo $value->event_id."<br />";
echo $spid."<br />";
}
This only outputs the first space_id and I need to get all the space_ids within "space_reservation" array. Not all records will have multiple space_ids. Any help pointing me in the right direction is appreciated. Not sure if I should use xpath but I need to re-write my foreach statement regardless.
I was hoping to be able to literally convert all references to "object(SimpleXMLElement)#_ (#)" to "array(#)"
[10]=> array (28) {
["reservation_id"]=> string(7) "8210614"
["event_id"]=> string(6) "279215"
["space_reservation"]=> array(2) {
[0]=> array (9) {
["space_id"]=> string(4) "3760"
["space_name"]=> string(9) "205"
["formal_name"]=> string(33) "Center" }
[1]=> array (9) {
["space_id"]=> string(4) "3769"
["space_name"]=> string(9) "207"
["formal_name"]=> string(32) "Right" } } }
}
the function in my cakephp 1.3 controller is this:
$xml = simplexml_load_string($string);
$this->data['events']= $xml->children();
$resdata = $this->data['events'];
$this->set('resdata',$resdata);
I think this should do what you are looking for:
foreach ($resdata as $res) {
echo $res->event_id . '<br />';
foreach ($res->space_reservation as $reservation) {
echo $reservation->space_id . '<br />';
}
}
Googled it and found a general solution for any SimpleXMLElement to array conversion:
function xml2array($xml) {
$arr = array();
foreach ($xml as $element) {
$tag = $element->getName();
$e = get_object_vars($element);
if (!empty($e)) {
$arr[$tag] = $element instanceof SimpleXMLElement ? xml2array($element) : $e;
}
else {
$arr[$tag] = trim($element);
}
}
return $arr;
}

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