I have an array and it has two arrays inside of it...I am able to access what I want for the first row by doing this...
print_r( $_SESSION['shopcart']['cart']['qty']);
How would I write that in a foreach?
Thanks,
J
foreach($_SESSION['shopcart']['cart']['qty'] as $value) {
echo $value;
}
you would do something like this:
to dump the array: $_SESSION['shopcart']['cart']
foreach($_SESSION['shopcart']['cart'] as $key=>$value){
echo $key." => ".$value."<br/>";
}
If you want to iterate through multiple dimensions, you can nest foreach as follows:
foreach($_SESSION['shopcart'] as $cart) {
foreach ($cart as $qty) {
// do something
}
}
Though I'd need a little more information about the array structure and what you really want to do in order to provide usable code, this is probably in the right ballpark.
I would recommend you you do do like this:
foreach($_SESSION['shopcart'] as $key=>$value){
if(is_array( $value ) ){
foreach($value => k1 => $v1){
//do something here if array
echo $k1." => ".$v1."<br/>";
}
}else{
//do something here if not array
}
}
Related
I am having a really bad time right now, since everyone on the internet is saying that PHP supports multidimensional arrays that are two, three, four, five, or more levels deep. However, arrays more than three levels deep are hard to manage for most people. So I can't find someone to help me.
A very simple example below
$documents = array(
array(
"name"=>"Markos",
"lastname"=>"papadopoulos",
"country"=>"Greece",
"nationality"=>"greek",
"job"=>"web developer",
"hobbies"=>array(
"sports"=>"boxing",
"others"=>array(
"freetime"=>"watching Tv"
)
)
)
);
foreach($documents as $document){
echo $document['name']."<br>"
.$document['lastname']."<br>"
.$document['country']."<br>"
.$document['nationality']."<br>"
.$document['job']."<br>";
foreach ($document['hobbies'] as $key=>$value){
echo $key." ".$value."<br>";
foreach ($value['others'] as $subkey=>$subvalue){
echo $subkey['freetime'];
}
}
}
I am stuck, I can't display the "others"=>array("freetime"=>"watching tv") can anyone advice me? And if I had also another array in the "others"=>array("freetime"=>"watching tv"), how could I display that array to? I am trying to learn the logic.
foreach ($documents as $key) {
echo $key['name']. '<br>';
echo $key['lastname']. '<br>';
echo $key['country']. '<br>';
echo $key['nationality']. '<br>';
echo $key['job']. '<br>';
echo $key['hobbies']['sports']. '<br>';
echo $key['hobbies']['others']['freetime']. '<br>';
}
output will be
Markos
papadopoulos
Greece
greek
web developer
boxing
watching Tv
In PHP, foreach actually have two syntaxes:
foreach($array as $element) this might means $element ends up being an array
foreach($array as $key => $value) this means that key will never be an array, it is what the key, so what you have before the => in your array, while $value can be an array.
Here is the way to follow the first syntax, mind that you don't even have to nest foreach here, as pointed out by #Nathanael's comment what you have in your array is mostly scalar, not really nested arrays.
foreach($documents as $document){
echo $document['name']."<br>".
$document['lastname']."<br>".
$document['country']."<br>".
$document['nationality']."<br>".
$document['job']."<br>".
$document['job']."<br>".
$document['hobbies']['sports']."<br>".
$document['hobbies']['others']['freetime'];
}
If you want to go in the second syntax, then it would be even better to make a recursion:
function display_multi_level_array($array) {
foreach($array as $key => $value){
if(is_array($value)) {
display_multi_level_array($value);
continue;
}
echo $key." ".$value."<br>";
}
}
display_multi_level_array($documents);
try
foreach($documents as $document){
echo $document['name']."<br>"
.$document['lastname']."<br>"
.$document['country']."<br>"
.$document['nationality']."<br>"
.$document['job']."<br>";
foreach ($document['hobbies'] as $key=>$value){
if (is_array($value)) {
foreach ($value as $subkey=>$subvalue){
echo $subvalue;
}
} else {
echo $key." ".$value."<br>";
}
}
}
If I have array like this myarray[0]['field1','field2','field3'];
I know its basically one row and has nothing to loop through, but i need it to loop through the values rather than the whole array. In this case it would need to loop 3x but if there were 10 fields, it should loop 10x.
I've been doing this but it feels too complicated for something so simple. Is there a function that is eluding me on google for this?
foreach (myarray[0][field1] as $item){
//do something
}
foreach (myarray[0][field2] as $item){
//do something
}
foreach (myarray[0][field3] as $item){
//do something
}
Use nested loops:
foreach ($myarray[0] as $field => $field_array){
foreach ($myarray[0][$field] as $item) {
//do something
}
}
You have a 2-dimensional array, but you want to only consider the second dimension? So treat the first dimension as a variable:
foreach ($myarray[0] as $item){
echo $item;
}
If you want to know the field name and value, then:
foreach ($myarray[0] as $key=>$value){
echo $key . ' = ' . $value;
}
foreach ($myarray[0] as $field => $field_array){
foreach ($field_array as $item) {
//do something
}
}
I have an array which looks like this:
$example = [
['rendered'][0]['rendereditem1']
['rendered'][4]['rendereditem2 and more']
['rendered'][2]['rendereditem3']
]
Now I want to iterate with foreach to get the contents of 0,4,2!
Normally I would write:
foreach($example as $value){
print $value['rendered'][int which is the same everywhere];
}
But that is obviously not working because the array name is always different...how could I iterate in this case?
Simply add a second loop to iterate over the members :
foreach($example as $value) {
foreach($value['rendered'] as $key=>$item) {
// Do what you want here, $key is 0,4,2 in your example
}
}
I am trying to solve the following problem:
Note I am new to programming and PHP and working through SAMS PHP, MySQL and Apache (Julie C. Meloni).
There is an exercise where a multidimensional array has to be created. The outer array is an associative array listing the genres of movies. The genre arrays list movies of that genre. You are then asked to print out a list of genres with the list of films associated with that genre.
My code:
<?php
$genres = array(
'Science Fiction' => array('Star Trek', 'Star Wars', 'Alien'),
'Drama' => array('Les Amant de Pont Neuf', 'War & Peace', 'Bridehead Revisited'),
'Crime' => array('Heat', 'Pulp Fiction', 'Messerine')
);
$gKeys = array_keys($genres);
foreach ($gKeys as $genre) {
print $genre."<br/>";
}
?>
This works and prints out:
Science Fiction
Drama
Crime
Here's where I am running into a wall. When I try adding another foreach loop after
print $genre;
no results appear in the browser (except results of first loop). I have tried everything. For example:
starting by using the array_value() function applied to $genre and then try a foreach on the array returned.
In the textbook there is also a while (list($x) = ($y)) mechanism mentioned.
I thoroughly re-read the array chapter and have looked elsewhere to no avail.
perhaps I have structured the multidimensional array incorrectly? Do the second dimensional arrays need to be associative arrays also for consistency?
Your array is structured correctly. You're taking wrong array (array of just the keys) and adding another foreach loop after print $genre; hence it is not working.
No, it is not required for second dimensional arrays to be associative arrays as well.
<?php
$genres = array(
'Science Fiction' => array('Star Trek', 'Star Wars', 'Alien'),
'Drama' => array('Les Amant de Pont Neuf', 'War & Peace', 'Bridehead Revisited'),
'Crime' => array('Heat', 'Pulp Fiction', 'Messerine')
);
foreach ($genres as $genre => $movies)
{
print $genre . " - <br/>";
foreach ($movies as $movie)
{
print $movie . "<br/>";
}
print "</br>";
}
?>
Wait! Why are you doing:
$gKeys = array_keys($genres);
This just gives you a single array of keys.
Do your first loop on $genres, then inside:
foreach ($genre as $key=>$subgenre)
{
//do stuff here
}
foreach ($genres as $genrekey => $genrevalue) {
print $genrekey."<br/>";
foreach ($genrevalue as $value) {
print $value."<br/>";
}
}
function multiarray_keys($ar) {
foreach($ar as $k => $v) {
$keys[] = $k;
if (is_array($ar[$k]))
$keys = array_merge($keys, multiarray_keys($ar[$k]));
}
return $keys;
}
$gKeys = multiarray_keys($genres);
echo "<pre>";
print_r(multiarray_keys($array));
echo "</pre>";
Your outer array is an associative array with genres as keys.
To print out movies of that genre (the subarrays), use another foreach as follows:
print "<ul>";
foreach ($genres as $genre => $movies) {
print "<li>".$genre."<ul>";
foreach ($movies as $movie) {
print "<li>".$movie."</li>";
}
print "</ul></li>";
}
print "</ul>";
If you need this for seeing what data goes in an array for debugging purposes you could use PHPs var_export(), var_dump(), print_r() only to make sure the data is getting populated as you want it to. Otherwise if you want to show it in production you could do some like this:
foreach($multiDimentinalArray as $key => $value):
if(is_array($value)):
foreach($value as $k => $val):
print " $key.$k => $val";
else:
print "$key => $value";
endif;
endforeach;
I'm trying to nicely output a data array (with Kohana v2.3.4), and am thinking there has to be a more efficient and elegant way to do this. My array looks like this:
array('category_id' => value, 'category_title' => value, 'posts' => array( 'id' => value, 'title' => value, ... ))
And here's how I'm outputting it in my view (some array values are omitted from this example for the sake of simplicity):
foreach($data as $d) {
echo '<h3>'.$d['category_title'].'</h3>';
foreach($d['posts'][0] as $p) {
echo '<p>'.$p['title'].$p['id'].'</p>';
}
}
Is there a better way to go about this with the array I have?
You can't escape from using nested loop (unless if you use array_walk etc) but you can make do without using lots of string concatenation by taking advantage of variable substitution:
foreach($data as $d) {
echo "<h3>{$d['category_title']}</h3>";
foreach($d_posts[0] as $p) {
echo "<p>{$p['title']} {$p['id']}</p>";
}
}
You can also combine it with extract() for cleaner strings:
foreach($data as $d) {
extract($d, EXTR_PREFIX_ALL, 'd_');
echo "<h3>$d_category_title</h3>";
foreach($d_posts[0] as $p) {
extract($p, EXTR_PREFIX_ALL, 'p_');
echo "<p>$p_title $p_id</p>";
}
}
Apart from a minor error:
foreach ($data as $d) {
echo '<h3>'.$d['category_title'].'</h3>';
foreach($d['posts'] as $p) {
echo '<p>'.$p['title'].$p['id'].'</p>';
}
}
no there isn't.
What's your issue with a nested loop for this?