469,326 Members | 1,351 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 469,326 developers. It's quick & easy.

Multi-Dimensional Arrays Help - And Other Questions on Arrays

348 100+
For some reason, I have always had a hard time understanding arrays as they pertain to php and databases. I understand associative arrays just fine but when there are multidimensional arrays, I kinda don't.

I have gone over a few different examples but they were limited. I was able to find one piece of code that I would like to disect and ask questions about so I can gain a better understanding.

Expand|Select|Wrap|Line Numbers
  1. $characters = array
  2. (
  3.   array ( name=>"name 1"
  4.   , occupation=>"developer"
  5.   , age=>30
  6.   , specialty=>"Java"
  7.   ),
  8.   array
  9.   (
  10.     name=>"name 2"
  11.     , occupation=>"Programmer"
  12.     , age=>24
  13.     , specialty=>"C++"
  14.   ),
  15.   array
  16.   (
  17.   name=>"name 3"
  18.   , occupation=>"designer"
  19.   , age=>63
  20.   , specialty=>"Javascript"
  21.   )
  22. );
  23.  
  24. foreach ($characters as $val)
  25. {
  26.   foreach ($val as $key=>$final_val)
  27.   {
  28.     print "$key: $final_val<br>";
  29.   }
  30.   print "<br>";
  31. }
In this code, the way I am reading this is that there are 3 "rows"??? or blocks of data. Each one of these rows or blocks has several other rows inside of it. I don't have a problem with the arrays per se but more the foreach loop. If I am incorrect about these 3 arrays being rows, please feel free to correct me.

On the foreach, can someone please tell me exactly how and why it is set up the way it is? Specifically, I don't understand why the coder didn't use a key/value pair. He only uses a value, then inside the loop he uses $key=>$final_val. What I need to understand is why and when to refer to or use the key value pair and when not to. I have also seen code written inside the foreach loop like so: $key['something'] = $val;

What is that? What exactly does it do? If any one can help me to understand these, I would be forever grateful. I have pulled my hair out for the last time on drawing my data out of an array.

Thanks.
Apr 21 '09
110 5622
fjm
348 100+
OK, yes, thanks. I see it. A 7D array. Because we have a second row that just repeats on line 22. :) Thanks for setting me straight.

Now, as we speak, I am trying to use a foreach to get some data back out but am not too successful. Here is what I currently have.
Expand|Select|Wrap|Line Numbers
  1. <?php
  2. $pages = array
  3. (
  4.   array
  5.   (
  6.     "Title" => "First page"
  7.     , "Tables" => array
  8.     (
  9.       array
  10.       (
  11.         "Title" => "First table"
  12.         , "Rows" => array
  13.         (
  14.           array
  15.           (
  16.             "Cells" => array
  17.             (
  18.               "Col1"
  19.               , "Col2"
  20.               , "Col3"
  21.             )
  22.           ),
  23.         )
  24.       )
  25.     )
  26.   )
  27. );
  28.  
  29. foreach($pages as $page)
  30. {
  31.   foreach($page as $key1=>$val1)
  32.   {
  33.     foreach($val1 as $key2 => $val2)
  34.     {
  35.       print_r($key2);
  36.     }
  37.   }
  38. }
  39. ?>
My problem is that I am getting lost and can't follow inside the arrays. Where am I where I left off? By my print_r?
Apr 21 '09 #51
Dormilich
8,651 Expert Mod 8TB
@Ciary
Expand|Select|Wrap|Line Numbers
  1. $pages = array
  2. (
  3.   array
  4.   (
  5.     "Title" => "First page",
  6.     "Tables" => array 
  7.     ( // I don't see any names in this array
  8.       array
  9.       (
  10.         "Title" => "First table",
  11.         "Rows" => array
  12.         ( // neither in this
  13.           array
  14.           (
  15.             "Cells" => array
  16.             ( // nor this
  17.               "Col1", "Col2", "Col3"
  18.             )
  19.           ),
  20.         )
  21.       )
  22.     )
  23.   )
  24. );
  25.  
Apr 21 '09 #52
fjm
348 100+
@fjm
EDIT: Line 22 of my past post not this one. I cit the array into one segment. 7D only.
Apr 21 '09 #53
fjm
348 100+
@Dormilich
I agree with you. Atli wrote it so I'm not really sure why he wrote it like that. I told him what I was trying to do and he told me that I needed an array that would hold the data. Based on my requirements, of course.

Isn't the arrays that you point out just holding the other arrays? Arn't they needed?
Apr 21 '09 #54
Dormilich
8,651 Expert Mod 8TB
@fjm
it depends on what data. since the array is well structured, you can also access some arrays directly. (e.g. there is usually no need to loop through the array holding the Title and the according Table)

the only array prone to looping are pages, Tables, Rows and Cells
Apr 21 '09 #55
Ciary
247 Expert 100+
ok srr dormilich you're right. didnt didnt notice

as an answer why u use ($arr as $key => $value) instead of ($arr as $value). the choice depends on what you want to do. if you want to alter your array, you'll need a key to do this:

Expand|Select|Wrap|Line Numbers
  1. $arr[$key] = $newVal;
because this doesnt work:
Expand|Select|Wrap|Line Numbers
  1. $value = $newVal;
but if you dont need a key(for example when you just want to read it's values) you use ($arr as $value).
it isn't neccessary though. if you want to be sure or if you get confused while using. just use the long method (($arr as $key => $value)). this always works.
Apr 21 '09 #56
Dormilich
8,651 Expert Mod 8TB
@fjm
I don't know, what requirements there were, but the array design seems obvious. an array for each important level, so far he didn't make it over-complicated, only thorough. (especially when you know the DOM (do you want some reading for that? :Ž))
@fjm
I needed to show Ciary, that there are 4 array levels with numeric keys
Apr 21 '09 #57
fjm
348 100+
@Dormilich
Ok, I remember what I was trying to do with this array back then. What I wanted to do was build a page out using html. Synamically build a page with n-amount of tables and n-columns. The loops would grab the data from the database and build each page dynamically. Now that I look at the code again where you made your notations, I believe those area were for where I was going to put my html. Not certain though.

If I wanted to use a 4each to get the col1, etc... what would that look like? I can't seem to get it.
Apr 21 '09 #58
Dormilich
8,651 Expert Mod 8TB
@fjm
once you're in the Cells array:
Expand|Select|Wrap|Line Numbers
  1. foreach ($cells as $cell)
  2. {
  3.     echo '<td>', $cell, '</td>';
  4. }
Apr 21 '09 #59
fjm
348 100+
@Dormilich
That's my million dollar question.. :) How to get there. I mean. My thinking is that it is a 7D array so in order for me to get into the col array, wouldn't I need 7 "nested" foreach loops? That is my thinking anyhow. Am I wrong?
Apr 21 '09 #60
fjm
348 100+
*bump* Accidentally posted when I wanted to edit. Sorry..
Apr 21 '09 #61
Dormilich
8,651 Expert Mod 8TB
@fjm
you need 3 loops to get there*.
Expand|Select|Wrap|Line Numbers
  1. foreach($pages as $page)
  2. {
  3.     foreach ($page['Tables'] as $table)
  4.     {
  5.         foreach ($table['Rows'] as $row)
  6.         {
  7.             foreach ($row['Cells'] as $cell) { // see previous post }
  8.         }
  9.     }
  10. }
* the cells loop, that is
Apr 21 '09 #62
fjm
348 100+
@Dormilich
OK, thanks. That actually helps me to understand better. Let me ask you this Dormilich.. You say it will take me 3 loops to get there but I count 4 loops. Was the 3 a typo?
Apr 21 '09 #63
Dormilich
8,651 Expert Mod 8TB
you need three loops to reach the Cells loop (the fourth, which was posted first).
Apr 21 '09 #64
fjm
348 100+
Ok. I think I understand. I know one thing.. that is that I fee much more comfortable being able to get my data out of a 2D array than before. I am going to have to study this a bit because honestly, it has me baffled a bit.

How long would you say it will take me to get this down; to really learn it? I mean, I totally understand the concept but all of the different arrays has my head spinning. I can't make the mental connection. :)
Apr 21 '09 #65
Ciary
247 Expert 100+
Expand|Select|Wrap|Line Numbers
  1. foreach($pages as $page){
  2.   echo "<h1>".$page['Title']."</h1><br/>";
  3.   foreach($page['tables'] as $table){
  4.     echo "<h3>".$table['Title']."</h3><br/>";
  5.     echo "<table>";
  6.     foreach($table['rows] as $row){
  7.       echo "<tr>";
  8.       foreach($row as $cell){
  9.         echo "<td>".$cell."</td>";
  10.       }
  11.       echo "</tr>";
  12.     }
  13.     echo "</table>";
  14.   }
  15. }
  16.  
this is the full code to add title etc.

to understand it wont take long. just try keep practising
Apr 21 '09 #66
Dormilich
8,651 Expert Mod 8TB
@fjm
practice, practice, practice and to and fro some sleep ;)

how long this takes you I can't tell, a good abstraction ability will help shortening it… maybe don't rely too much on the table visualization (if it goes beyond 2D)
Apr 21 '09 #67
fjm
348 100+
I think I see something..

Expand|Select|Wrap|Line Numbers
  1. $pages = array  <-- value
  2. (
  3.   array  <-- key
  4.   (
  5.     "Title" => "First page"
  6.     , "Tables" => array
  7.     (
  8.       'a'=>'b',
  9.       array <-- value
  10.       (
  11.         "Title" => "First table"
  12.         , "Rows" => array
  13.         (
  14.           'c'=>'d',
  15.           array <-- key
  16.           (
  17.             'e'=>'f',
  18.             "Cells" => array <-- value
  19.             (
  20.               "Col1"
  21.               , "Col2"
  22.               , "Col3"
  23.             )
  24.           )
  25.         )
  26.       )
  27.     )
  28.   )
  29. );
Is this right?
Apr 21 '09 #68
Dormilich
8,651 Expert Mod 8TB
@Ciary

there's no need to put breaks after the headings, you can set those layout stuff better with CSS.
Apr 21 '09 #69
Dormilich
8,651 Expert Mod 8TB
@fjm
add <-- key to lines 6, 12
Apr 21 '09 #70
Ciary
247 Expert 100+
i know, it's a habbit of me to always break after an echo.
Apr 21 '09 #71
Dormilich
8,651 Expert Mod 8TB
@Ciary
I don't mean the line break in the source code, I mean the <br> element. (and if I got this wrong, you didn't <br> after every echo…)
Apr 21 '09 #72
fjm
348 100+
I truly think I understand this better. Thanks guys! Also Ciary, I used your code and it also worked as did Dormilich's code. What I am going to do now is to study this and make myself some new examples to use. I won't stop until I fully understand them.

Arrays are really cool and I am really beginning to see the benefits of using whenever I can.
Apr 21 '09 #73
Dormilich
8,651 Expert Mod 8TB
@fjm
that's what I call professional attitude. you're always welcome.

@fjm
wait ’til you see objects… ;)
Apr 21 '09 #74
Ciary
247 Expert 100+
your welcome :)
(.................i feel brainwashed..................) ^^

for the <br/> i'm learning not to but its stronger then myself. :)
Apr 21 '09 #75
fjm
348 100+
@Dormilich
Thanks to BOTH of you guys. You guys are fantastic as are alot of the other guys that have helped me so much including Atli and Pbmods. This is a great forum and I sincerley appriciate all the help that you guys continue to extend to me. As if I haven't said it enough. Thanks a lot guys and thanks for sticking with me on this.

Also.. I kind of have a bad habit of putting the cart before the horse.. I have been using objects for about a year now. Unless your talking about something other than class objects that is. :)
Apr 21 '09 #76
Dormilich
8,651 Expert Mod 8TB
@fjm
well, I found arrays way easier to understand than objects with all their OOP philosophy attached…

the prospect of fetching DB data into object arrays is always thrilling…
Apr 21 '09 #77
fjm
348 100+
@Dormilich
lol.. Ah yes.... record. I have been using that for a little while now. See.. for me, arrays were WAY harder to get a real grasp on. It's kind of like this for me.. I have been programming for about a year and a half now and I feel like I have reached a state where I almost feel embarrassed for not understanding arrays that well. I had an opportunity to talk to another PHP programmer the other day and we were talking about objects and I didn't even break a sweat. But when he started talking about arrays, I just cringed. I have no idea why they have been so hard for me. I do know that having my DBAL with the fetch_array set to BOTH didn't help me because I could never seem to figure out exactly what was going on.

I am not by any means an expert on objects and truly feel that I have grazed the surface but I feel like I write better and cleaner code and that is my #1 priority. The better I can code, the happier I am. :)
Apr 21 '09 #78
fjm
348 100+
Hey Ciary, are you still with me?
Apr 21 '09 #79
Ciary
247 Expert 100+
i'm still with you, but i dont have much to say about objects. i dont know much about them.

object are to me what arrays were to you :)
Apr 21 '09 #80
fjm
348 100+
@Ciary
That's cool. I still myself don't fully understand them. I still struggle with objects too. :)

Listen... in your code.. I am getting a foreach error on this line:
foreach($table['Rows'] as $row)

I cannt for the life of me, see it. Can you?

EDIT: Invalid argument supplied for foreach()
Apr 21 '09 #81
Ciary
247 Expert 100+
did you correct my 'rows to 'Rows'? if thats not the problem try using $table[1] and see if u still get the problem.
Apr 21 '09 #82
fjm
348 100+
OK, yes, I did originally correct the rows to Rows and that didn't work. I just now tried foreach($table[1] as $row) but now I get an offset error.
Apr 21 '09 #83
Dormilich
8,651 Expert Mod 8TB
post the array, maybe we see something…
Apr 21 '09 #84
Ciary
247 Expert 100+
what do you get if you replace the foreach with this.
Expand|Select|Wrap|Line Numbers
  1. var_dump[$table]
what do you get as output?
Apr 21 '09 #85
fjm
348 100+
Ok here is everything that I have so far.

Expand|Select|Wrap|Line Numbers
  1. $pages = array
  2. (
  3.   array
  4.   (
  5.     "Title" => "First page"
  6.     , "Tables" => array
  7.     (
  8.       'a'=>'b',
  9.       array
  10.       (
  11.         "Title" => "First table"
  12.         , "Rows" => array
  13.         (
  14.           'c'=>'d',
  15.           array
  16.           (
  17.             "e"=>"f",
  18.             "Cells" => array
  19.             (
  20.               "Col1"
  21.               , "Col2"
  22.               , "Col3"
  23.             )
  24.           )
  25.         )
  26.       )
  27.     )
  28.   )
  29. );
  30.  
  31. foreach( $pages as $page )
  32. {
  33.   echo "<h1>" . $page['Title'] . "</h1><br/>";
  34.   foreach( $page['Tables'] as $table )
  35.   {
  36.     echo "<h3>" . $table['Title'] . "</h3><br/>";
  37.     echo "<table>";
  38.     foreach($table['Rows'] as $row)
  39.     {
  40.       echo "<tr>";
  41.       foreach( $row as $cell )
  42.       {
  43.         echo "<td>" . $cell . "</td>";
  44.       }
  45.       echo "</tr>";
  46.     }
  47.     echo "</table>";
  48.   }
  49. }
Apr 21 '09 #86
Ciary
247 Expert 100+
if you remove the 'a' => 'b', 'c' => 'd' and 'e' => 'f' it will work
Apr 21 '09 #87
fjm
348 100+
Ok, here's my var_dump:
Expand|Select|Wrap|Line Numbers
  1. array(2) {
  2.   ["Title"]=>
  3.   string(11) "First table"
  4.   ["Rows"]=>
  5.   array(2) {
  6.     ["c"]=>
  7.     string(1) "d"
  8.     [0]=>
  9.     array(2) {
  10.       ["e"]=>
  11.       string(1) "f"
  12.       ["Cells"]=>
  13.       array(3) {
  14.         [0]=>
  15.         string(4) "Col1"
  16.         [1]=>
  17.         string(4) "Col2"
  18.         [2]=>
  19.         string(4) "Col3"
  20.       }
  21.     }
  22.   }
  23. }
Apr 21 '09 #88
Ciary
247 Expert 100+
solution is posted above :)
Apr 21 '09 #89
fjm
348 100+
Got it Ciary. Thanks. I removed them and I no longer have the error but don't have the columns echoing to the browser. Instead, I get the dreaded "Array". :\
Apr 21 '09 #90
Dormilich
8,651 Expert Mod 8TB
line 41: replace $row with $row['Cells']
Apr 21 '09 #91
Ciary
247 Expert 100+
yep, just noticed i forgot it there :)
Apr 21 '09 #92
fjm
348 100+
Your good Mr. Dormilich! :) You too Ciary.. This is exactly what I mean when I say that you have to really understand HOW arrays work before you can even troubleshoot them. I think that has always been my frustration. I looked at the code over half a dozen times and didn't see that. Now, it is so plain..
Apr 21 '09 #93
fjm
348 100+
can i ask one more question pleeeeeese?? before I let you guys go to sleep? :)

Why is it foreach( $row['Cells'] as $cell ) and not foreach( $rows as $cell )

Why isn't it the same?
Apr 21 '09 #94
Ciary
247 Expert 100+
i must say, it was because i missed an "array(" so gigantic arrays can even trouble the best coders (i'm not one of them). biggest problem with someone elses code is you might see problems differently. thats why its very difficult to find your own errors.
Apr 21 '09 #95
Dormilich
8,651 Expert Mod 8TB
with such large structures, it's easy to loose oversight…
Apr 21 '09 #96
Ciary
247 Expert 100+
because there is an array after 'rows' before 'cells'. i didnt notice it at first

edit: and its way to early for us to go to sleep but thanks for the concern :)
Apr 21 '09 #97
fjm
348 100+
I know what you mean Ciary.. I have a hard time finding my own errors some times too. In fact... some of the absolute hardest errors for me have been array errors. I can usually find out whats going on but when I cannot get the correct result set, I wind up like a dog chasing his tail. That's why I am here today. I figured that I had better get down to business and start asking some serious questions. It's kinda like a doctor that can successfully preform an operation on your brain but doesn't know how to remove a wart. :)
Apr 21 '09 #98
fjm
348 100+
@Ciary
Thanks.. As for me.. its 6:30 am and I haven't been to sleep yet. Now you can see why my wife hates me. :) I spend all night coding. Since I have started programming, coffee and sleepless nights have become my best friend.
Apr 21 '09 #99
Ciary
247 Expert 100+
sleeples nights and 12 cups of coffee each hour. sounds like paradise :)

EDIT WOOHOO 100 posts
Apr 21 '09 #100

Post your reply

Sign in to post your reply or Sign up for a free account.

Similar topics

4 posts views Thread by OutsiderJustice | last post: by
37 posts views Thread by ajikoe | last post: by
4 posts views Thread by Frank Jona | last post: by
23 posts views Thread by Kaz Kylheku | last post: by
17 posts views Thread by =?Utf-8?B?R2Vvcmdl?= | last post: by
1 post views Thread by CARIGAR | last post: by
reply views Thread by harlem98 | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.