tags:

views:

518

answers:

3

Is there way to return a two dimensional array from a SQL query? Like..

"SELECT id, x, y, z FROM test"

..and have it return as id => x, y, z? I could do a loop and create a second array but I imagine that's extra work that I might not have to do. Just not familiar with SQL right now.

A: 

SQL already returns 2D sets of data -- multiple rows, each with the same fields per row. When you SELECT id, x, y, z FROM test, it'll return the id, x, y, and z values for every row in test. id is associated with x, y, and z because it's returned in the same row.

If you want a PHP data structure that maps id values to x, y, and z, you'll have to do the SELECT statement and build this data structure from the result set.

Kaleb Brasee
You talk about multiple rows. But mysql in same time can return only one row, so:MySQL can't return 2D set. It can return or one-dimensional array (mysql_fetch_row) or associative array (mysql_fetch_assoc).
Vitaly Dyatlov
Yeah, I meant that ALL of the rows combined is a 2D set.
Kaleb Brasee
+3  A: 

In PHP, SQL queries will only return result sets. Rows and columns.

You need a further loop in order to process it into an array of the kind that you are referring to. That's no problem, and should be part of your database wrapper if you use it frequently.

$result = mysql_query(...);
$aData = array();
while($row = mysql_fetch_assoc($result))
   $aData[$row['id']] = array($row['x'], $row['y'], $row['z']);
gahooa
you can save one line the $aData = array(); in not nessesary
streetparade
@streetparade: set your warning level to `E_ALL | E_STRICT` and you will see that the array initialization is actually needed.
gahooa
+1  A: 

The answer to your question is no, there's no way to do that.

Relational databases are essentially two-dimensional structures. They can represent relations between structures, but all the data is stored in a flat, two-dimensional way, and queried and returned as such. Unfortunately, there is no concept of data structures in the same way that programming languages have them. Any result you get from an SQL query is always going to be a scalar data set of fields and values. PHP makes this a little easier by returning the column names as array keys, and the field values as array values, but that's as far as you can get.

In order to put your results into a multi-dimensional array, you'll have to do it with PHP after you've fetched the results from the database.

zombat