Jump to content

SIMPLE QUESTION - LOOPING AN ARRAY


jayfray84

Recommended Posts

Hi there,

 

I have the following PHP code:

 

<?php

 

$books = array(

array("title"=>"Book Title 1", "author"=>"Author 1", "publisher"=>"Publisher 1"),

array("title"=>"Book Title 2", "author"=>"Author 2", "publisher"=>"Publisher 2"),

array("title"=>"Book Title 3", "author"=>"Author 3", "publisher"=>"Publisher 3"),

);

 

foreach ($books as $key => $value) {

echo "$key : $value<br>";

}

 

?>

 

 

I'm trying to loop through this code, but all it outputs is:

 

0: ARRAY

1: ARRAY

2: ARRAY

 

-- It's not even pulling the proper $keys and $values. It works when there's just ONE array -- but not with this multidimensional array.

 

Any ideas?

 

Thanks!

J

Link to comment
https://forums.phpfreaks.com/topic/228251-simple-question-looping-an-array/
Share on other sites

<?php

$books = array(
array("title"=>"Book Title 1", "author"=>"Author 1", "publisher"=>"Publisher 1"),
array("title"=>"Book Title 2", "author"=>"Author 2", "publisher"=>"Publisher 2"),
array("title"=>"Book Title 3", "author"=>"Author 3", "publisher"=>"Publisher 3"),
);

foreach ($books as $key => $value) {
foreach($value as $kk => $vv) {
   echo "$kk : $vv<br>";
}
}

?>

Yes, books is a multidimensional array.  That means you have an array, nested inside of another array.  You can have as many dimensions as you need, however, at this juncture you have 2 dimensions.

 

So, your first foreach loop, goes through the first dimension, and looks at each key (starts at 0).  This is why your numbers start as 0 - 2, however now your values are returning array, this is because the values are the second dimension of your array, or as some call it, nested.

 

The second foreach loop, goes through the second dimension of your arrays, now we can access the keys (title, author, publisher) and the values.  Since your array doesn't have any more dimensions, these values are not ARRAY's but STRINGS.  You can echo out strings.

 

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.