Multi-Dimensional Arrays Help - And Other Questions on Arrays

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • fjm
    Contributor
    • May 2007
    • 348

    #1

    Multi-Dimensional Arrays Help - And Other Questions on Arrays

    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 multidimensiona l 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.

    Code:
    $characters = array
    (
      array ( name=>"name 1"
      , occupation=>"developer"
      , age=>30
      , specialty=>"Java"
      ),
      array
      (
        name=>"name 2"
        , occupation=>"Programmer"
        , age=>24
        , specialty=>"C++"
      ),
      array
      (
      name=>"name 3"
      , occupation=>"designer"
      , age=>63
      , specialty=>"Javascript"
      )
    );
    
    foreach ($characters as $val)
    {
      foreach ($val as $key=>$final_val)
      {
        print "$key: $final_val<br>";
      }
      print "<br>";
    }
    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_va l. 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.
  • Dormilich
    Recognized Expert Expert
    • Aug 2008
    • 8694

    #2
    firstly, the posted code should give you quite a bunch of error notices (the keys are set as constants, which I doubt are intended)

    if you're familiar with Maths, imagine arrays as matrices where you can access each element with the appropriate index (aka key) values (like $array[$i][$j][$k]). the sample would correspond to a 3x4 matrix.

    Originally posted by fjm
    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_va l.
    the reason for not using a key/value pair in the first loop is, that the keys are not needed by the program/coder (they are numeric values). in the first foreach he loops through the topmost array getting an array as value ($val) (gettype($val) would give you "array") then he loops over that value/this array and prints the keys ($key) and values ($final_val) of this sub-array.

    foreach can be used in 2 ways, so you can use the syntax you really need:
    Code:
    // values only
    foreach ($array as $value)
    
    //keys and values
    foreach ($array as $key => $value)
    Originally posted by fjm
    What I need to understand is why and when to refer to or use the key value pair and when not to.
    it depends on what you want to do, if you don't need the keys you omit them.

    Originally posted by fjm
    I have also seen code written inside the foreach loop like so: $key['something'] = $val;
    looks strange, I need to see the whole code (part) to explain.

    Comment

    • Ciary
      Recognized Expert New Member
      • Apr 2009
      • 247

      #3
      Originally posted by Dormilich
      Originally posted by fjm
      I have also seen code written inside the foreach loop like so: $key['something'] = $val;
      looks strange, I need to see the whole code (part) to explain.
      shouldn't that be something like this?
      Code:
      $array[$key]=$val;
      or for an associative array:
      Code:
      $array['something']=$val
      in this case, it's used to write to the array in a foreach loop to change its values. next is a multidimentiona l example based on your array.

      Code:
      $i = 0;
      foreach($array as $key => $val){
         $val[0] = "changedname " + $i;
         $i ++;
         $array[$key] = $val;
      }
      this code changes the first value on each row to "changednam e " and the row number. to do this you need a key but mostly you wont use it. mostly, you need it when you want to write to the array.

      the code as you wrote it cant be right. it states that your $key is an array. or it could be a foreign library i dont know about.

      Comment

      • fjm
        Contributor
        • May 2007
        • 348

        #4
        Originally posted by Dormilich
        firstly, the posted code should give you quite a bunch of error notices (the keys are set as constants, which I doubt are intended)
        Hey Dormilich, thanks for the help. Actually, I ran the code and I don't have any errors or notices and my server is set for E_ALL.

        Originally posted by Dormilich
        if you're familiar with Maths, imagine arrays as matrices where you can access each element with the appropriate index (aka key) values (like $array[$i][$j][$k]). the sample would correspond to a 3x4 matrix.
        I'm thinking in terms of tables here. Are you saying that your sample would correspond to a table with 1 row and 4 cells? That's what I am seeing.

        Originally posted by Dormilich
        the reason for not using a key/value pair in the first loop is, that the keys are not needed by the program/coder (they are numeric values). in the first foreach he loops through the topmost array getting an array as value ($val) (gettype($val) would give you "array") then he loops over that value/this array and prints the keys ($key) and values ($final_val) of this sub-array.
        Since I have posted, I have been looking for that code sample that you didn't seem to understand as well as playing with MD arrays. BTW: Ciary was exactly correct on the code he posted. Please see his example for what I was trying to convey.

        In almost everything I do, I will always have my own key. I don't need php to generate the numeric key for me. So, that being the case, would a foreach loop be written any differently from the code that I posted to get my key?

        Originally posted by Dormilich
        foreach can be used in 2 ways, so you can use the syntax you really need:
        Code:
        // values only
        foreach ($array as $value)
        
        //keys and values
        foreach ($array as $key => $value)

        it depends on what you want to do, if you don't need the keys you omit them.


        looks strange, I need to see the whole code (part) to explain.
        What I understand from your example is that the first foreach you wrote would be good for an assoc array and the second would be for a MD array. Yes?

        Comment

        • fjm
          Contributor
          • May 2007
          • 348

          #5
          Originally posted by Ciary
          shouldn't that be something like this?
          Code:
          $array[$key]=$val;
          or for an associative array:
          Code:
          $array['something']=$val
          in this case, it's used to write to the array in a foreach loop to change its values. next is a multidimentiona l example based on your array.

          Code:
          $i = 0;
          foreach($array as $key => $val){
             $val[0] = "changedname " + $i;
             $i ++;
             $array[$key] = $val;
          }
          this code changes the first value on each row to "changednam e " and the row number. to do this you need a key but mostly you wont use it. mostly, you need it when you want to write to the array.

          the code as you wrote it cant be right. it states that your $key is an array. or it could be a foreign library i dont know about.
          Hi Ciary. That's cool! Thanks for the explanation.

          Here is what has been happening that has been making me pull my hair out for the past 7 months with regard to arrays. I have a class that gets my results from my database. The method uses mysql_fetch_arr ay and returns the values. Well, along with my key/value pairs, would be an identical, duplicate row of data with the array integer and I could never seem to figure out how to omit the int values. As it turned out, the mysql_fetch_arr ay() in my method used "MYSQL_BOTH " and was the culprit. I changed it to MYSQL_ASSOC and I have been golden ever since. I still want to learn more about arrays though because I have reached a point of understanding where I see that arrays are really helpful in transporting my data in bulk and I can work with it and do whatever I want with it.

          Comment

          • Dormilich
            Recognized Expert Expert
            • Aug 2008
            • 8694

            #6
            Originally posted by fjm
            Actually, I ran the code and I don't have any errors or notices and my server is set for E_ALL.
            well, I got the expected 12 notices…

            Originally posted by fjm
            I'm thinking in terms of tables here. Are you saying that your sample would correspond to a table with 1 row and 4 cells? That's what I am seeing.
            for a two-dimensional array you can think in terms of tables. but it would be a 3(4) row / 4(3) column table (depending upon where you set the precedence).

            Originally posted by fjm
            What I understand from your example is that the first foreach you wrote would be good for an assoc array and the second would be for a MD array. Yes?
            No, the first is if you're only interested in the values. the type of the keys doesn't matter at all.

            Comment

            • Dormilich
              Recognized Expert Expert
              • Aug 2008
              • 8694

              #7
              Originally posted by fjm
              As it turned out, the mysql_fetch_arr ay() in my method used "MYSQL_BOTH " and was the culprit.
              as described in the manual. if you run into such problems, it is always a good idea to read all of the manual entry (even the comments). this solves most of these problems

              Comment

              • Ciary
                Recognized Expert New Member
                • Apr 2009
                • 247

                #8
                you're welcome :)

                to answer the other question:

                a matrix looks like a table with rows and columns. actually thats how arrays work 2. but you also have more dimensions as 2. good example:
                Code:
                $_SESSION["foo"][][][]
                $_SESSION is a standard array provided by php. you can put 3 dimentional array in it. in that way, you have a 4D array(there isn't a way to visualize this though).
                i hope this isnt making it 2 difficult.

                if you already have the key wihout the foreach. you dont need the foreach
                example: i want to change the element on row 4 column 8:
                Code:
                   $array[3][7] = $val;
                note that an array starts at 0 so thats why i lowered my indexes by 1

                for the different ways of foreach:
                use the one with the key to write and the one without the key to read unless you need the key for something else.

                i hope i havent complicated things :)

                EDIT: srr for the double post Dormilich. seems like we were posting at the same time

                Comment

                • fjm
                  Contributor
                  • May 2007
                  • 348

                  #9
                  Originally posted by Dormilich
                  as described in the manual. if you run into such problems, it is always a good idea to read all of the manual entry (even the comments). this solves most of these problems
                  Well, let's just say that I'm hard headed and sometimes hate to read. Honestly though, I would not have known about that if someone would not have pointed it out to me.

                  I really had no idea why I was getting duplicated rows. Now that I have read the manual on the fetch_array function, I feel more comfortable now and can finally concentrate on understanding arrays more. I could never figure out if it was me writing a bad loop or if something else was going on or both.

                  Comment

                  • fjm
                    Contributor
                    • May 2007
                    • 348

                    #10
                    Originally posted by Dormilich
                    well, I got the expected 12 notices…
                    From my ini file: error_reporting = E_ALL & ~E_NOTICE | E_STRICT
                    I just ran the code again and got nothing. Completely clean. I'm on version 5x

                    Originally posted by Dormilich
                    for a two-dimensional array you can think in terms of tables. but it would be a 3(4) row / 4(3) column table (depending upon where you set the precedence).
                    OK so if I understand.. An array over 2D doesn't look like a table? Sometimes I need to visualize something to understand it. I'm also not that familier with maths. I did manage to find a matrix and it resembled a table, kind of.

                    Comment

                    • fjm
                      Contributor
                      • May 2007
                      • 348

                      #11
                      Originally posted by Ciary
                      a matrix looks like a table with rows and columns. actually thats how arrays work 2. but you also have more dimensions as 2.
                      Maybe I have a better example. Are these MD arrays kind of like nested tables? If yes, then I can certanly picture it. :)

                      Comment

                      • Ciary
                        Recognized Expert New Member
                        • Apr 2009
                        • 247

                        #12
                        a table is a 2 dimentional array. and all other MD arrays are exacly as nested tables :)

                        Comment

                        • Dormilich
                          Recognized Expert Expert
                          • Aug 2008
                          • 8694

                          #13
                          Originally posted by fjm
                          error_reporting = E_ALL & ~E_NOTICE | E_STRICT
                          that means: report all errors except notices and compatibility warnings

                          there's a whole section explaining this *nudgenudge*

                          Originally posted by fjm
                          OK so if I understand.. An array over 2D doesn't look like a table? Sometimes I need to visualize something to understand it. I'm also not that familier with maths. I did manage to find a matrix and it resembled a table, kind of.
                          well, yes. although it gets complicated for 3-dimensionals and unimaginable for more than 4 dimensions.

                          Comment

                          • fjm
                            Contributor
                            • May 2007
                            • 348

                            #14
                            Wow guys... OK... So let me recap... So we have a 2D array that resembles a table. Then we have a higher level of dimensions that we can say looks like nested tables. Kind of like sayins that each cell can have an array inside of it and it just keeps going from there. Maybe an example.

                            Code:
                            <table>  <-- array 1
                              <tr>
                                <td>
                                  <table>  <-- array 2
                                    <tr>
                                      <td>
                                        <table>  <-- array 3
                                          <tr>
                                            <td>
                                              Etc..
                                            </td>
                                          </tr>
                                        </table>
                                      </td>
                                    </tr>
                                  </table> 
                                </td>
                              </tr>
                            </table>
                            Am I correct? 3D array?

                            Comment

                            • fjm
                              Contributor
                              • May 2007
                              • 348

                              #15
                              Originally posted by Dormilich
                              that means: report all errors except notices and compatibility warnings
                              OK, you win. :) Actually, yesterday I wrote some code and knew that I should have gotten an undefined index but didn't. I was wondering why and figured that it had something to do with the new changes I made.

                              It's really strange because with those ini values, I now get new messages that I didn't get before like the usual date() timezone error so I thought that it was a stricter ruleset. Thanks for the heads up Dormilich! If I wanted to have a strict set of rules, would I just ise E_ALL? (I'll still read the link you provided.)

                              Comment

                              Working...