1 回答

TA貢獻1998條經(jīng)驗 獲得超6個贊
您可以在應用程序層中轉換數(shù)據(jù),以便在結果數(shù)組中,您將只有表 a 的行以及相關的類別名稱。
首先,您需要一個有序的結果集,例如
select a.id,
? a.phone,
? a.name,
? b.category?
from table_1 a
join table_2 b?
? on a.id = b.table_1_id
order by a.id asc
然后遍歷所有記錄并烘焙數(shù)據(jù)集
$result = [];
$currentParent = false;
$data = null;
foreach ($rows as $row) {
? ? /*?
? ? ?* if id is changed then its a different record
? ? ?* prepare data for new row and create a comma separated string of category names
? ? ?*/
? ? if ($currentParent != $row['id']) {
? ? ? ? if($data != null){ // for first and intermediate rows
? ? ? ? ? ? $result[]= $data;
? ? ? ? }
? ? ? ? $data = ['name'=> $row['name'], 'category'=> ''];
? ? ? ? $currentParent = $row['id'];
? ? }
? ? $data['category'] = empty($data['category']) ? $row['category']: $data['category'] .", ". $row['category'];
}
$result[]= $data; // add data for last row
echo json_encode($result);
生成的數(shù)組將如下所示
Array
(
? ? [0] => Array
? ? ? ? (
? ? ? ? ? ? [name] => item 1
? ? ? ? ? ? [category] => Cat 1, Cat 2, Cat3
? ? ? ? )
? ? [1] => Array
? ? ? ? (
? ? ? ? ? ? [name] => item 2
? ? ? ? ? ? [category] => Cat 1, Cat 2, Cat3
? ? ? ? )
? ? [2] => Array
? ? ? ? (
? ? ? ? ? ? [name] => item 3
? ? ? ? ? ? [category] => Cat 1, Cat 2, Cat3
? ? ? ? )
)
另一種速記方法但不優(yōu)選是在查詢級別應用聚合方法,例如如果您使用 MySQL,您可以使用group_concat
但它有最大字符限制(可調(diào))的限制。
- 1 回答
- 0 關注
- 122 瀏覽
添加回答
舉報