JOIN in an associative array instead of separated records
Table stores
id name date
1 foo 2011-06-15 15:10:34
2 bar 2011-07-02 16:45:18
Table locations
storeid zipcode latitude longitude
1 90001 xxxxx xxxxx
1 45802 xxxxx xxxxx
2 32843 xxxxx xxxxx
How can i produce an associative array that contains a key called locations
which is an array of a开发者_JAVA百科ll locations of a store?
My current SQL ( which separate each location in a record ):
SELECT stores.*, locations.* FROM locations INNER JOIN stores ON stores.id = locations.storeid
Example of what i want:
array(
[0] => array(
"id" => 1,
"name" => "foo",
"locations" => array(
[0] => array(
"zipcode" => 90001,
"latitude" => -45.48513,
"longitude" => 82.12432
)
[1] => array(
"zipcode" => 42802,
"latitude" => -31.48513,
"longitude" => 77.12432
)
)
)
)
and so on for other stores...
Thanks
So you can't extract the data in one query because SQL normally works per row and hasn't got data structure like PHP arrays. You can't nest the records using JOIN. That's why you'll have to do it with with separate queries in a PHP loop. Like so:
$query = "SELECT s.id,s.name FROM stores AS s";
$result = mysql_query($query);
$data = array();
while($row = mysql_fetch_assoc( $result )) {
$data[] = $row['id'];
$data[] = $row['name'];
$query2 = "SELECT l.zipcode, l.latitude, l.longitude FROM locations AS l WHERE storeid=".$row['id'];
$result2 = mysql_query($query2);
while($row2 = mysql_fetch_assoc( $result )) {
$data['locations']['zipcode'] = $row2['zipcode'];
$data['locations']['latitude'] = $row2['latitude'];
$data['locations']['longitude'] = $row2['longitude'];
}
}
Otherwise you can grab all results with JOIN and do as follows:
$query = "SELECT * FROM stores AS s
LEFT JOIN locations AS l
ON s.id = l.storesid";
$result = mysql_query($query);
$data = array();
while($row = mysql_fetch_assoc( $result )) {
$data[$row[id]]['id'] = $row['id'];
$data[$row[id]]['name'] = $row['name'];
$data[$row[id]]['locations'][] = array($row['zipcode'], $row['latitude'], $row['longitude']);
}
But this will make the main array's index to be set not sequential starting from 0 but each index will be equal to the ID of the "store" item
精彩评论