从数据库结果构建多维数组

时间:2012-05-10 10:49:52

标签: php mysql

您好我有一组数据库结果,我需要将其组织成一个多维数组,以便我可以通过一封电子邮件而不是多封电子邮件将用户的结果通过电子邮件发送给用户。

我从db获得的值是name,email,route_name,route_details。理想情况下,我想根据用户的电子邮件将路由分组在一起,因为这是他们唯一的标识符。我认为以下内容对我有用。

    Array
    (
       [email@email.com] => Array
                          (
                            [0] => name
                            [1] => Array
                                 (
                                   [0] => route_name
                                   [1] => route_details
                                 )
                             [2] => Array
                                 (
                                   [0] => route_name
                                   [1] => route_details
                                 )
                           )
       [email2@email2.com] => Array
                          (
                            [0] => name
                            [1] => Array
                                 (
                                   [0] => route_name
                                   [1] => route_details
                                 )
                            [2] => Array
                                 (
                                   [0] => route_name
                                   [1] => route_details
                                 )
                            [3] => Array
                                 (
                                   [0] => route_name
                                   [1] => route_details
                                 )

                           )
    )

我非常感谢任何帮助我在结果循环中尝试了以下内容,但我不确定如何根据电子邮件对结果进行分组,我认为这不是我需要的。

    $routeArray = array($data->email ,array($data->route_name, $data->route_details));

    $userEmailArray[] = $flightArray;

由于

1 个答案:

答案 0 :(得分:0)

我认为以下内容适合您。此代码将添加键名而不是数字索引。

// Add order by email clause
$sql = "select name, email, route_name, route_details from YOUR SQL QUERY ORDER BY    email";
$res = mysql_query($sql);

$desired_format = array();

while($row = mysql_fetch_assoc($res)){
    $tmp = array('route_name'=>$row['route_name'],'route_details'=>$row['route_details']);
    $desired_format[$row['email']]['name'] = $row['name'];
    $desired_format[$row['email']][] = $tmp;
}