On 9/30/09 Wed  Sep 30, 2009  11:33 AM, "Bruce Ferrell"
<bferr...@baywinds.org> scribbled:

> 
> 
> Shawn H Corey wrote:
>> Bruce Ferrell wrote:
>>> I have a database (mysql if it matters) and I can select columns and
>>> rows from it no problem.  what I can't quite seem to see how to do is to
>>> take the columns I can select and put them into a 2 dimensional array.
>>> 
>>> I tried this:
>>> 
>>> @data = $sth->fetchrow_array();
>>> 
>>> and it got a two dimensional array of one element each and this:
>>> 
>>> @rtn = $sth->fetchrow_array();
>>> push(@data,@rtn) seems to get me a giant 1 dimensional array.
>>> 
>>> I'm sort of at a loss
>>> 
>>> TIA
>>> 
>>> Bruce
>>> 
>> 
>> You have to create an array of arrays.
>> 
>>   push @data, [ @rtn ];
>> 
>> See:
>> perldoc perldsc  http://perldoc.perl.org/perldsc.html
>> perldoc perllol  http://perldoc.perl.org/perllol.html
>> perldoc perldata http://perldoc.perl.org/perldata.html
>> 
>> 
> OK if I read these right and I understand the results of my experiments
> correctly, this:
> 
> @rtn = $sth->fetchrow_array();
> 
> is giving me an array with two elements and this:
> 
> push @data, [ @rtn ];
> 
> is giving me an array of 2 element arrays.  Not good as what I want is 2
> arrays each the length of the total rows returned.  What it seems I need
> to do is something like this:
> 
> my ( $current_level, $time ) = $sth->fetchrow_array();
> 
> push @data[0][#]->$current_level;
> push @data[1][#]->$time;
> 
> ... repeat until out of rows
> 
> Is that correct notation to add the variable to the end of the array(s)?

No. Apparently what you want is

    push( @{$data[0]}, $current_level);
    push( @{$data[1]}, $time);

You could also define two separate arrays:

    my @current_levels;
    my @times;

and fill them with similar statements:

    push( @current_levels, $current_level);
    push( @times, $time);

and put links to them in @data:

    my @data = ( \...@current_levels, \...@times );

Some would consider that a poor choice of data structure, as your pairs of
elements are only associated by using a common index.

    for my $row ( 0..$#{$data[0]} ) {
        my $level = $data[0]->[$row];
        my $time = $data[1]->[$row];
    }

There is no guarantee that the two arrays even have the same number of
elements.

Most people would prefer Shawn's scheme:

    push( @data, [ $current_level, $time ]);

The two data elements are very closely associated. You can sort them by time
and extract them together:

    for my $row ( sort {$a->[1] <=> $b->[1]} @data ) {
        my{ $level, $time ) = @$row;
    }

which is much more difficult to do in the first case.

So why do you think you need to have two arrays the same length containing
data from different rows?




-- 
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/


Reply via email to