Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning a two dimensional array from SQL query

Tags:

sql

php

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.

like image 993
Gerardo Calixto Aquino Avatar asked Sep 06 '25 16:09

Gerardo Calixto Aquino


1 Answers

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']);
like image 108
gahooa Avatar answered Sep 08 '25 10:09

gahooa