Donald Donald - 1 year ago 65
PHP Question

how can i display the records from the SQl server database in an array using PHP

I have an online Job application site, where I am trying to query the positions from database(MS SQL Server).

I have queried the database using

, where I am getting the position list in an array.

But I would like to display the array in this format.


$select = array (
'Province1' =>
array (
'City1' =>
array (
ID => 'Position1',
ID => 'Position2',
'Province2' =>
array (
'City2' =>
array (
ID => 'Position3',
ID => 'Position4',


![enter image description here][1]

I am currently using this code:

$tsql = "SELECT * FROM Jobs";
$stmt = sqlsrv_query( $conn, $tsql);
while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_NUMERIC)) {
echo "".$row[0]."<br>\n";
echo "".$row[1]."<br>\n";
echo "".$row[2]."<br>\n";
echo "".$row[3]."<br>\n";

Please see the screen shot of the page

Answer Source

A basic way to do this is to just define the different levels of grouping in your result array as you fetch rows from your query result:

while ($row = sqlsrv_fetch_object($stmt)) {
    $result[$row->Province][$row->City][$row->ID] = $row->Position;

Each time you want another level of grouping in your result, just add another key like I've shown there.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download