如何在单独的PHP数组下“分组”SQL结果

时间:2018-05-29 15:36:24

标签: php mysql sql

我找不到这个解决方案,因为我甚至不知道如何用一句话正确解释它... 我有这种SQL表

id    name    type    locale 
-----------------------------   
1     foo     video   en
2     bar     video   en 
3     baz     pdf     fr

我想查询它最终得到这个PHP数组

$array = 
[
    'en' => 
        [
            [
                'name' => 'foo',
                'type' => 'video',
            ], 
            [
                'name' => 'bar',
                'type' => 'video',
            ],
        ],
    'fr' => [
                'name' => 'baz',
                'type' => 'pdf',
            ]
]

我怎样才能做到这一点?谢谢!

1 个答案:

答案 0 :(得分:1)

请考虑以下事项:

<?php

/*
DROP TABLE IF EXISTS my_table;

CREATE TABLE my_table
(id SERIAL PRIMARY KEY
,name VARCHAR(12) NOT NULL
,type VARCHAR(12) NOT NULL
,locale CHAR(2) NOT NULL
);

INSERT INTO my_table VALUES
(1,'foo','video','en'),
(2,'bar','video','en'),
(3,'baz','pdf','fr');

SELECT id, name, type, locale FROM my_table ORDER BY id;
+----+------+-------+--------+
| id | name | type  | locale |
+----+------+-------+--------+
|  1 | foo  | video | en     |
|  2 | bar  | video | en     |
|  3 | baz  | pdf   | fr     |
+----+------+-------+--------+
*/

require('path/to/connection/stateme.nts');

$query = "
SELECT id, name, type, locale FROM my_table ORDER BY id;
";

$result = mysqli_query($db,$query) or die(mysqli_error());

$old_array = array();

while($row = mysqli_fetch_assoc($result)){

$old_array[] = $row;

}


$new_array = array();

foreach($old_array as $row){
$new_array[$row['locale']][] = $row['name'];
}

print_r($new_array);

?>

输出:

Array
(
    [en] => Array
        (
            [0] => foo
            [1] => bar
        )

    [fr] => Array
        (
            [0] => baz
        )

)