• Status: Solved
• Priority: Medium
• Security: Public
• Views: 159

# two dimetional arrays from query

Would you explain two dimetional arrays to me? I know how to make simple one dimentional array from query. But I cannot understand well two dimentional arrays made from query. If someone explain it to me with breaking each steps into pieces, I greatfully appricate it.
portal123
0
portal123
• 3
1 Solution

Senior Software DeveloperCommented:
A 1 dimensional array is a list.

e.g.

<?php
\$a_1d_array = array(1,2,3,4,5,6,7,8,9,10);
?>

A 1 dimensional array is like a table (excel or DB).

e.g.

<?php
\$a_2d_array = array(
array(1,2,3,4,5,6,7,8,9,10),
array(2,4,6,8,10,12,14,16,18,20),
);
?>

A function like mysql_fetch_arry() will get 1 row of a result set from a query and return it as a 1d array.

If you wanted to add this 1d array to an array of rows (effectively cloning the result set), then you would use code like ...

\$a_my_2d_array[] = \$a_db_row;

This says, simplistically, add the \$a_db_row as a new element to the \$a_my_2s_array variable.

This constructs an 2d array primarily sorted by rows from the DB.

Remember DBs do NOT use arrays (normally). You need to talk in terms of rows.

A PHP variable can be multi-dimensional. Though I think upon reflection PHP actually uses nested 1d arrays (an element in an array can be an array).

e.g.
<?php
\$a_many_array = array
(
array
(
array(1,2,3),
array(2,3,4),
array(5,6,7),
array(1,2,3),
),
array
(
array(1,2,3),
array(2,3,4),
array(5,6,7),
array(1,2,3),
),
array
(
array(1,2,3),
array(2,3,4),
array(5,6,7),
array(1,2,3),
),
array
(
array(1,2,3),
array(2,3,4),
array(5,6,7),
array(1,2,3),
),
array
(
array(1,2,3),
array(2,3,4),
array(5,6,7),
array(1,2,3),
),
array(1,2,3),
array(2,3,4),
array(5,6,7),
array(1,2,3),
);
?>

You don't have to populate the entire matrix either. Spare arrays are the norm with PHP.

What else do you want to know?
0

Author Commented:
Thanks your explanation. Whats function can i usually use to apply two dimentional arrays into  an actual shape?? If you do not mind, would you please make a simple table from two dimetional arrays for me??

portal123
0

Senior Software DeveloperCommented:
Something along these lines maybe?

<?php
\$s_SQL = 'SELECT col1, col2, col3 FROM table';
\$r_results = xxxx_query(\$s_SQL, \$r_conn);
\$a_array = array();
while (False !== (\$a_row = xxxx_fetch_assoc(\$r_results)))
{
\$a_array[] = \$a_row;
}
?>

The xxxx is dependent upon your DB (mysql, mssql, etc).

But the principle is to get a lot of rows (1 row is a 1D array) into an array of rows (2D array ordered by row number).

0

Senior Software DeveloperCommented:
Thank you.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.