How to access array elements - php

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

Related

I got a working array but my code isn't working to display each row of multidimensional array

I am using a working function that perfectly displays the contents of a csv file.
function csv2array( $filename, $delimiter )
{
// read the CSV lines into a numerically indexed array
$all_lines = #file($filename);
if( !$all_lines )
{
return FALSE;
}
$csv = array_map( function( &$line ) use ( $delimiter )
{
return str_getcsv( $line, $delimiter );
}, $all_lines );
// use the first row's values as keys for all other rows
array_walk( $csv, function( &$a ) use ( $csv )
{
$a = array_combine( $csv[0], $a );
});
array_shift( $csv ); // remove column header row
return $csv;
}
$items = csv2array( 'filetest.csv', ';' );
//print_r( $items );
echo '<pre>';
var_dump( $items );
echo '</pre>';
The var_dump output is perfect and displays:
array(40) {
[0]=>
array(4) {
["Jurisdiction"]=>
string(2) "AL"
[" Total Distance(mi.)"]=>
string(7) "1730.68"
[" Off Road(mi.)"]=>
string(4) "2.63"
[" Toll Road(mi.)"]=>
string(1) "0"
}
[1]=>
array(4) {
["Jurisdiction"]=>
string(2) "AR"
[" Total Distance(mi.)"]=>
string(6) "826.27"
[" Off Road(mi.)"]=>
string(4) "1.35"
[" Toll Road(mi.)"]=>
string(1) "0"
}
[2]=>
array(4) {
["Jurisdiction"]=>
string(2) "DE"
[" Total Distance(mi.)"]=>
string(5) "49.11"
[" Off Road(mi.)"]=>
string(4) "0.34"
[" Toll Road(mi.)"]=>
string(4) "6.57"
}
I am trying to display the values of those $rows which sounds super easy but I am getting empty values and searched the internet and cannot find the right way to do it. Here is my code:
foreach($items as $row)
{
echo $row[0]. " ".$row[1]." ".$row[2]."TESTTEST<br>";
}
but I only get the TESTTEST results but the total number of times it displays TESTTEST is correct but the values are empty so what am I missing? I searched this site and others and they seem easy but mine isn't working. Thanks.
What you could do is nest the loop or implode it.
Nesting:
foreach($items as $row)
{
foreach($row as $val){
echo $val . " ";
}
echo "TESTTEST<br>";
}
Or implode:
foreach($items as $row)
{
echo implode(" ", $row);
echo "TESTTEST<br>";
}
You shouldn't use a numerical index for the data as you've just added the column name as the index.
But you can just implode() the data anyway...
foreach($items as $row)
{
echo implode(" ", $row)."TESTTEST<br>";
}
Thanks for the help everyone I got it the way I want and can expand from here on out. I was looking for this code:
$i = 0;
foreach($items as $row)
{
echo $row['Jurisdiction'] . $row[' Total Distance(mi.)'] . "TESTTEST<br>";
$i++;
}
echo 'total: ' . $i;
I will be sure to trim out the space on the names.

PHP - echo an array within a session array

So I'm trying to use a foreach loop to echo out all the values of an array in my $_SESSION array as follows.
<?php
foreach($_SESSION['movie'] as $key => $value){
echo "Movie: " . $key;
}
foreach($_SESSION['session'] as $key => $value){
echo "Session: " . $key;
}
?>
I'm pretty new to PHP so don't have much idea if I'm even on the right track.
This is the var_dump of the $_SESSION array.
array(1) {
["cart"]=> array(2) {
["ACWED-09"]=> array(3) {
["movie"]=> string(2) "AC"
["session"]=> string(6) "WED-09"
["seats"]=> array(1) { ["SF"]=> int(7) }
}
["ACFRI-09"]=> array(3) {
["movie"]=> string(2) "AC"
["session"]=> string(6) "FRI-09"
["seats"]=> array(1) { ["SF"]=> int(2) }
}
}
}
The movie is nested in the $_SESSION['cart'] array. You need to do:
foreach ($_SESSION['cart'] as $key => $item) {
echo "Key: $key<br>";
if (isset($item['movie']) {
echo "Movie: {$item['movie']}<br>";
}
if (isset($item['session']) {
echo "Session: {$item['session']}<br>";
}
}
You should try this..
foreach($_SESSION['movie'] as $key => $value) {
echo 'Movie ' . $value . '<br/>';
}
echo '<hr/>';
foreach($_SESSION['session'] as $key => $value) {
echo 'Session' . $value . '<br/>';
}
An array pairs values to keys, as stated here. Keys are the indexes in the array.
foreach($_SESSION['movie'] as $key => $value){
echo "At the index " . $key . ", the movie is " . $value;
}
So you should go with echo "Movie: " . $value; if you want to write the value. The key isn't relevant here.
Note that you don't have to use the "$key => $value" pairing if you don't care about the indexes within your loop. This works too :
foreach($_SESSION['movie'] as $value){
echo "Movie: " . $value;
}
You don't have access to the value's index in that case.
foreach($_SESSION['movie'] as $key => $value){
echo "Movie: " .$key."=". $value;
}
foreach($_SESSION['session'] as $key => $value){
echo "Session: " .$key."=". $value;
}
Here is an example for associative array what is key and what is value
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
foreach($age as $x => $x_value) {
echo "Key=" . $x . ", Value=" . $x_value;
echo "<br>";
}
echo '<pre>';
print_r($_SESSION);
echo '</pre>';
foreach ($_SESSION['cart'] as $key => $item) {
echo "Key: $key<br>";
echo "Movie: {$item['movie']}<br>";
echo "Session: {$item['session']}<br>";
}

How to loop to this array

i have this array as output.
array(2) { ["Datum"]=> string(10) "2017-05-29" ["ID"]=> array(2) { [2]=> string(19) "75528705-1431953348" [3]=> string(21) "1081357825-1445504448" } }
how can i loop through this array in php ?
this is the code to read the array
<?php
var_dump($_POST);
$val = $_POST;
?>
I have already try this
<?php
foreach($_POST->ID as $val) {
print "waarde = " . $val . " <BR>";
}
?>
This is a declaration of your provided $_POST array:
$_POST=array(
"Datum" => "2017-05-29",
"ID" => array(
2 => "75528705-1431953348",
3 => "1081357825-1445504448"
)
);
You can directly access any of its elements by referencing its keys:
echo $_POST["Datum"]; // prints 2017-05-29
print_r($_POST["ID"]); // prints Array([2] => 75528705-1431953348 [3] => 1081357825-1445504448 )
echo $_POST["ID"][2]; // prints 75528705-1431953348
echo $_POST["ID"][3]; // prints 1081357825-1445504448
You are not dealing with an object, so the -> will not work.
Using a foreach loop on the $_POST["ID"] subarray will let you access all of the elements in the subarray.
Code:
foreach($_POST["ID"] as $val){
echo "waarde = $val<br>";
}
Output:
waarde = 75528705-1431953348
waarde = 1081357825-1445504448
<?php
foreach($_POST['ID'] as $index => $str) {
echo "waarde = " . $str . "<br/>";
}
?>

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.

How the get line by line keys and values of one level JSON in PHP

I am receiving a JSON array from Javascript as a $_POST variable.
I want to get all variables and its values of the JSON. I tried to use json_decode with foreach like bellow but it did not work. my php code is
<?php
$string = $_POST['json'];
var_dump(json_decode($string, true));
foreach($string as $key => $value) {
echo $key . " : " . $value;
}
?>
my json is
[{"EXTAPP_ID":"9901","CATEGORY_ID":"10","LANGUAGE_CODE":"tr","CATEGORY_LANG_DESC":"TR AAA"},{"EXTAPP_ID":"9901","CATEGORY_ID":"10","LANGUAGE_CODE":"de","CATEGORY_LANG_DESC":"DE AAA"},{"EXTAPP_ID":"9901","CATEGORY_ID":"20","LANGUAGE_CODE":"de","CATEGORY_LANG_DESC":"DE XXX"},{"EXTAPP_ID":"9901","CATEGORY_ID":"20","LANGUAGE_CODE":"tr","CATEGORY_LANG_DESC":"TR YYY"},{"EXTAPP_ID":"9901","CATEGORY_ID":"10","LANGUAGE_CODE":"en","CATEGORY_LANG_DESC":"EN ZZZ"},{"EXTAPP_ID":"9901","CATEGORY_ID":"20","LANGUAGE_CODE":"en","CATEGORY_LANG_DESC":"EN VVV"}]
it returns the request as a array like bellow (I did not paste all result)
array(6) {
[0]=>
array(4) {
["EXTAPP_ID"]=>
string(4) "9901"
["CATEGORY_ID"]=>
string(2) "10"
["LANGUAGE_CODE"]=>
string(2) "tr"
["CATEGORY_LANG_DESC"]=>
string(19) "TR XXX"
}
[1]=>
array(4) {
["EXTAPP_ID"]=>
string(4) "9901"
["CATEGORY_ID"]=>
string(2) "10"
["LANGUAGE_CODE"]=>
string(2) "de"
["CATEGORY_LANG_DESC"]=>
string(17) "TR YYY"
}
[2]=>
what I expected was
EXTAPP_ID: 9901
CATEGORY_ID:10
LANGUAGE_CODE:de
CATEGORY_LANG_DESC:DE AAA
Decode the string with $string = json_decode($_POST['json'], true);
You can get desired result by following code
$string = $_POST['json'];
$string = json_decode($string, true);
foreach($string as $value) {
foreach($value as $k=>$v) {
echo $k . " : " . $v .'<br/>';
}
echo '<hr>';
}
Try this instead:
$string = json_decode($_POST['json'], true);
foreach($string as $key => $value) {
echo $key . " : " . $value;
}
Try this:
$string = $_POST['json'];
$data = json_decode($string, true);
var_dump($data);
foreach($data as $key => $value) {
echo $key . " : " . $value;
}

Categories