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/>";
}
?>
Related
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.
I'm developing a pizza's restaurant ecommerce and now I'm trying to get the size (Familiar) and the ingredients (Pernil dol�, Bac�, Emmental) of a pizza that was ordered previously. The data I want to get (the italic values in this paragraph) becomes serialized from database:
a:4:{s:10:"attributes";a:2:{s:6:"Tamany";a:1:{i:3;s:8:"Familiar";}s:11:"Ingredients";a:3:{i:318;s:12:"Pernil dol�";i:270;s:5:"Bac�";i:294;s:8:"Emmental";}}s:9:"shippable";s:1:"0";s:4:"type";s:5:"pizza";s:6:"module";s:10:"uc_product";}array(4) { ["attributes"]=> array(2) { ["Tamany"]=> array(1) { [3]=> string(8) "Familiar" } ["Ingredients"]=> array(3) { [318]=> string(11) "Pernil dol�" [270]=> string(4) "Bac�" [294]=> string(8) "Emmental" } } ["shippable"]=> string(1) "0" ["type"]=> string(5) "pizza" ["module"]=> string(10) "uc_product" }
I discovered 'unserialized' php method and I tried this:
$attr = $row['data']; // data from database
$data = preg_replace('!s:(\d+):"(.*?)";!e', "'s:'.strlen('$2').':\"$2\";'", $attr); // I did this because I get some errors...
After I did that, I got this multidimensional array (a bit more human readable):
array(4) { ["attributes"]=> array(2) { ["Tamany"]=> array(1) { [3]=> string(8) "Familiar" } ["Ingredients"]=> array(3) { [318]=> string(11) "Pernil dol�" [270]=> string(4) "Bac�" [294]=> string(8) "Emmental" } } ["shippable"]=> string(1) "0" ["type"]=> string(5) "pizza" ["module"]=> string(10) "uc_product" }
Next step was try to loop the resulting data with a foreach loop, like the following:
foreach($data['attributes'] as $item)
{
print '<ul>';
foreach($item as $value)
{
print_r('<li>' . $value . '</li>');
}
print '</ul>';
}
I'm a php beginner PHP developer and I can't figure out how can I loop this array in order to get the values I need. I'm getting this error:
Warning: Invalid argument supplied for foreach() in /home/my_host/public_html/dev.mysite.com/inc/file.php on line 79
Can anybody tell me how I have to loop this array to get the data?
Any help will be very, very appreciated.
Best regards,
I created this example for you. First I declared an array which believe mimics the array you have to parse. Then I looped through and outputed the contents of the array.
<?php
$array = array(
0 => array(
'0' => 'John Doe',
'1' => 'john#example.com'
),
1 => array(
'0' => 'Jane Doe',
'1' => 'jane#example.com'
),
);
foreach ($array as $key => $value) {
$thisArray = $array[$key];
print_r('<ul>');
foreach ($thisArray as $key2 => $value){
print_r('<li>'.$thisArray[$key2].'</li>');
}
print_r('</ul>');
}
?>
Finally, and based on the answer of #Gregory Hart, I reached my goal. This is the final code that makes it possible in my particular case:
$data = $row['data'];
$attrib = preg_replace('!s:(\d+):"(.*?)";!e', "'s:'.strlen('$2').':\"$2\";'", $data);
$attr = unserialize($attrib);
foreach ($attr as $key => $value)
{
print_r('<ul>');
$thisArray = $attr[$key];
foreach ($thisArray as $key2 => $value2)
{
print_r('<li>' . $key2 . ': ');
$thisArray2 = $attr[$key][$key2];
foreach ($thisArray2 as $key3 => $value3)
{
if ($key2 == 'Tamany')
print_r('<span class="label label-warning">' . utf8_encode($thisArray2[$key3]) . '</span> ');
if ($key2 == 'Ingredients')
print_r('<span class="label label-success">' . utf8_encode($thisArray2[$key3]) . '</span> ');
if ($key2 == 'Salsa')
print_r('<span class="label label-primary">' . utf8_encode($thisArray2[$key3]) . '</span> ');
}
print '</li>';
}
print_r('</ul>');
}
Thanks for you help!
Try this logic:
$data_unserialize = unserialize($row->data);
foreach ($data_unserialize as $data_key => $data_value) {
if($data_key =='size')
{
$thisArray = $data_unserialize[$data_key ];
foreach ($thisArray as $key2 => $value2){
if($key2=='attributes')
{
switch ($value2)
{
case "Pernil dol�":
echo'Pernil dol �';
break;
case "Emmental":
echo'Emmental';
break;
default:
echo 'Nothing';
}
}
}
}
}
NB:- And remove the break; from switch statement to display all ingrediants.
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.
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;
}
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>";
}