Jump to content

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.

 

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.