在做乙個專案的使用者列表的時候,需要將乙個使用者的多輛車放在一行顯示,但是普通查詢出來的結果是:
array
([0] => array
([id] => 29
[user_id] => 1
[car_no] => 234567
)[1] => array
([id] => 21
[user_id] => 1
[car_no] => 23565
)[2] => array
([id] => 23
[user_id] => 1
[car_no] => 12345
)[3] => array
([id] => 28
[user_id] => 1
[car_no] => 124455
)[4] => array
([id] => 6
[user_id] => 1
[car_no] => 12345
)[5] => array
([id] => 7
[user_id] => 2
[car_no] => 22
)[6] => array
([id] => 3
[user_id] => 2
[car_no] => 粵t863
)[7] => array
([id] => 25
[user_id] => 3
[car_no] => 12345
));
但是我們想要的結果是:
array(
[0] => array
([user_id] => 8
[login] => 18620982882
[car_no] => array
([0] => 粵a123))
[1] => array
([user_id] => 7
[login] =>
[car_no] => array
([0] => 粵t456
[1] => 123456))
[2] => array
([user_id] => 2
[login] => 13318029123
[car_no] => array
([0] => 粵t863
[1] => 22))
[3] => array
([user_id] => 1
[login] => 15088138542
[car_no] => array
([0] => 12345
[1] => 23565
[2] => 12345
[3] => 124455
[4] => 234567))
)
我之前的方法是:
private function group_sort($unique, $num, $data) }}
return $data_format;
}
乙個乙個遍歷,進行重組聚合,也可以到到效果,但是效率低下,**也比較複雜,今天查閱資料發現乙個簡單的方法,mysql本身有這個功能,可以把多個結果集成為一行,預設用逗號隔開,sql語句如下:
select user_id,group_concat(car_no) as car_no from mf_car_info group by user_id;
產生的結果:
array
( [0] => array
([user_id] => 1
[car_no] => 12345,23565,12345,124455,234567
)[1] => array
([user_id] => 2
[car_no] => 粵t863,22
)[2] => array
([user_id] => 3
[car_no] => sdfa,12345
)
這個就簡單多了,直接遍歷分割一下即可:
foreach ($data as $key => $value)
echo "";
print_r(json_encode($data));
echo "
";
完整**如下:
<?php
$dsn = 'mysql:dbname=***x;host=192.***.1.***;port=3306';
$username = 'ysp';
$password = '123456';
try catch (pdoexception $e)
$statement = "select id,user_id,group_concat(car_no) as car_no from mf_car_info group by user_id";
$rows = $pdo->query($statement);
//獲取總行數
// print_r($rows->rowcount());
//獲取所有結果
$data = $rows->fetchall();
foreach ($data as $key => $value)
echo "";
print_r(json_encode($data));
echo "
";
exit;
SQLserver 多行合併為一行
將表和插入模擬資料 create table test id int course varchar 255 insert into test values 1,語文 insert into test values 2,數學 insert into test values 3,英語 insert in...
mysql多行合併一行,一行拆分多行
資料 建表語句 drop table if exists 品牌 create table 品牌 id int 0 not null,品牌 varchar 255 character set utf8 collate utf8 general ci null default null engine i...
sqlserver字串多行合併為一行
建立測試表 ifobject id test is notnull drop table test create table dbo.test id intidentity 1,1 not null name varchar 50 null subject varchar 50 null sourc...