looping through a db and putting some info into array

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
toms100
Forum Contributor
Posts: 119
Joined: Wed Feb 26, 2003 10:29 am
Location: Bristol,UK

looping through a db and putting some info into array

Post by toms100 »

i have a database called buildings with amongst other things, 3 important things:
xcord << x cooridinate
ycord << y cooridinate
status << either SOLD, forsale, or forrent

ive done my sql query and have a variable called $buildings with the entire result in.
what i would like to do is creat an array, ie:
$location[Xcord][Ycord] = status

but i cant work out the best way to get the information from the database and put it in this array.
i think will will probably have to use two nested foreach statments, but im not sure :/

hope someone can help

Tom
McGruff
DevNet Master
Posts: 2893
Joined: Thu Jan 30, 2003 8:26 pm
Location: Glasgow, Scotland

Post by McGruff »

If you have a column like building name - or the old favourite auto-incrementing integer ID column (which I've called bid here):

Code: Select all

<?php

$mysql = "SELECT bid, xcord, ycord, status FROM table_name";
$query = mysql_query($mysql) or die("Cannot query the database.<br>" . mysql_error());

while($result = mysql_fetch_array($query)) {
    $bid = $result['bid'];
    $location[$bid]['xcord'] = $result['xcord'];
    $location[$bid]['ycord'] = $result['ycord'];
    $location[$bid]['status'] = $result['status'];
    unset($bid); 
}

?>
The unset() line won't be needed with an auto-incrementing integer column but if you use a "name" column, and a record doesn't have a name for some reason, the next loop would overwrite the previous one. Basically, the first key has to relate to a column which always has a value and the value is unique.

In a sense, the multi dimensional array $location is merely duplicating the $query resource: perhaps you need it for something - if not work with $query directly.
Post Reply