in reply to Re^10: Help with MySQL SELECT into multidimensional array
in thread Help with MySQL SELECT into multidimensional array

A hash of array would be much better because of the very inefficient search to match up the current id from query#2 with an id in column 1 (index 0) of the 2D array. The hash of hash is better still because we don't have to fool around with this "expand the array by another column stuff".

But to use just a single 2D array. $array[0][1] is the second element of the first row. If you have a reference to that row, then: $this_row_ref->[1] is the way. $row_ref->[-1] the -1 index means "last element".

A 2D array is an array of references to arrays. All multi-dimensional structures are references until you get to the last dimension.

#!/usr/bin/perl -w use strict; use Data::Dumper; use Data::Dump qw(pp); ###### some data to work with ###### #id #name my @clients = ( [123 , 'clientA'], #using this instead of SQL query [346 , 'clientB'], [789 , 'clientC']); #id #integer my @int_numbers = ( #[123, 33] #using this instead of SQL query [346 , 1], [789 , 2] ); ###### ###### my @Table2D; #using an Array of Array foreach my $row_ref (@clients) { my ($id, $name) = @$row_ref; #you get this from the first query push @Table2D, [$id,$name]; } print pp (\@Table2D), "\n"; # now the 2D array is started... # #[[123, "clientA"], [346, "clientB"], [789, "clientC"]] #now expand each row by one column foreach my $row_ref (@Table2D) { push @$row_ref, 0; } print pp (\@Table2D), "\n"; #[[123, "clientA", 0], [346, "clientB", 0], [789, "clientC", 0]] #now double loop ... #if we use a Hash of Array, we don't need this... #of course this is super inefficient foreach my $query_ref (@int_numbers) { # you get these from second query.. # my ($id2, $integer_number) = @$query_ref; foreach my $row_ref (@Table2D) { my ($id_in_table) = @$row_ref; #just the first column! if ($id_in_table == $id2) #searching table for the id { #in query 2. $row_ref->[-1] = $integer_number; last; #found... stop looking } } } print pp (\@Table2D), "\n"; # see now clientB and clientC got their last column updated # but clientA did not! #[[123, "clientA", 0], [346, "clientB", 1], [789, "clientC", 2]]