在关联数组中加入而不是分隔的记录

时间:2011-07-10 13:56:02

标签: php mysql

stores

id  name  date
1   foo   2011-06-15 15:10:34
2   bar   2011-07-02 16:45:18

locations

storeid  zipcode  latitude  longitude
1        90001    xxxxx     xxxxx
1        45802    xxxxx     xxxxx
2        32843    xxxxx     xxxxx

如何生成一个包含名为locations的键的关联数组,该键是商店所有位置的数组?

我当前的SQL(将记录中的每个位置分开):

SELECT stores.*, locations.* FROM locations INNER JOIN stores ON stores.id = locations.storeid

我想要的例子:

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
                                   )
                          ) 
         )
)
其他商店

等......

由于

1 个答案:

答案 0 :(得分:1)

因此,您无法在一个查询中提取数据,因为SQL通常每行都有效,并且没有像PHP数组那样的数据结构。您无法使用JOIN嵌套记录。这就是为什么你必须在PHP循环中使用单独的查询。像这样:

$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'];
    }
}

否则,您可以使用JOIN获取所有结果,并执行以下操作:

$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']);
}

但这会使主数组的索引设置为从0开始不连续,但每个索引将等于“store”项的ID