Undefined Arrays inside for loop

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • virtualweb
    New Member
    • Aug 2007
    • 30

    Undefined Arrays inside for loop

    Hello:

    Im working on a Hotel Reservtion script and ran into a little problem:
    I have 3 types of rooms, 1 is Single, 2 is Double, 3 is Suite
    for this reason, $totaltypes = '3'; (in the snippet below).

    I have a form with checkboxes in order to reserve rooms, all rooms that are checked are saved in the array @All_Rooms as detailed below:

    Code:
     = ("1-101", "1-102","2-201", "2-202","3-301", "3-302");
    1-101 means that room number 101 belongs to type 1 (being a single room).
    2-201 means that room number 201 belongs to type 2 (being a double room).
    and so forth.

    Now I need to remove all room numbers from the array @All_Rooms and put them in separate arrays by room type. In other words all rooms beginning with 1- would go in one array, all rooms beginning with 2- would go on another, and so forth.

    Except I never know how many room types will be, the script checks out this number by veryfying how many room type files have been created and assign it to the scalar $totaltypes.
    I tryed the following code but it doesnt work... what am I doing wrong..??
    Code:
    for($b=1; $b<=$totaltypes; $b++)
    {
    foreach $room (@all_rooms){
    @splitted_room = split (/\-/, $room);
    if($splitted_room[0] == $b){
    push(@Reserved_Rooms[$b], $splitted_room[1]);
    }
    }
    }
    Thanx beforehand
    VirtualWeb
    Last edited by eWish; Apr 13 '09, 11:53 PM. Reason: Removed BOLD tags
  • KevinADC
    Recognized Expert Specialist
    • Jan 2007
    • 4092

    #2
    Your best option to me sounds like using a hash of arrays. The type is the hash key and all the room numbers of that type will be the value of the key, which is an array. Something like:

    Code:
    my %Rooms;
    foreach my $room (@all_rooms){
       my ($t, $r) = split (/-/, $room);
       push @{$Rooms{$t}}, $r;
    }
    You then loop through the hash keys and the value of each hash key will have all the rooms associated with the type.

    Code:
    foreach my $type (keys %Rooms) {
       print "Room Type: $type\n";
       print "Rooms: ", join(' - ', @{$Rooms{$type}} , "\n\n";
    }

    Comment

    • virtualweb
      New Member
      • Aug 2007
      • 30

      #3
      Thank you.. your suggestion worked

      Thank you.. I had never seen a hash of arrays... it worked

      Code:
      my %Rooms;
      foreach my $room (@all_rooms){
         my ($t, $r) = split (/-/, $room);
         push @{$Rooms{$t}}, $r;
      }
      Last edited by eWish; Apr 13 '09, 11:53 PM. Reason: Removed BOLD tags

      Comment

      Working...