亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何從不同的表呈現數據表中單元格中的多行?

如何從不同的表呈現數據表中單元格中的多行?

PHP
元芳怎么了 2023-10-22 21:01:50
我正在使用數據表創建一個表,但在其中呈現數據時遇到了一些問題。我的表結構是。TABLE_1|------|------|-------||  ID  | NAME | PHONE ||------|------|-------|TABLE_2|------|------------|----------||  ID  | TABLE_1_ID | CATEGORY ||------|------------|----------|這是我的PHP代碼$db  = new Database; // Database connection$sql = "SELECT a.*, b.* FROM TABLE_1 a, TABLE_2 b WHERE a.ID = b.TABLE_1_ID";$exe = $db->select($sql);$result = array();foreach ($exe as $rows) {    $result[] = $rows;}echo json_encode($result);這是我的JavaScript$('#example').DataTable({    ajax: {        url:"data.php",        dataSrc:""    },    columns: [        {data:"NAME"},        {data:"CATEGORY"}    ]});到目前為止,一切正常,數據已完美加載。但問題是,假設我只有一行和 5 行,因此我的數據表生成 5 行,但我希望所有類別都在一個單元格中,我只想要一行而不是 5 行。TABLE_1TABLE_2TABLE_1.ID = TABLE_2.TABLE_1_ID我正在考慮在渲染函數中做一些事情,例如$('#example').DataTable({    ajax: {        url:"data.php",        dataSrc:""    },    columns: [        {data:"NAME"},        {            data:"ID",            render: function(data, type, row){                // Some stuff to render 5 Category in a single cell                // Using the ID from row.ID (maybe)                // how to return 5 CATEGORY in this cell            }        }    ]});但我真的不知道這個過程,谷歌+堆棧溢出+數據表論壇對我來說有點混亂,因為我不擅長Javascript。 你們能幫我做到這一點嗎?我必須在渲染功能中編寫什么類型的代碼或代碼才能在單個單元格中顯示 5 個類別。 提前謝謝。
查看完整描述

1 回答

?
米琪卡哇伊

TA貢獻1998條經驗 獲得超6個贊

您可以在應用程序層中轉換數據,以便在結果數組中,您將只有表 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

然后遍歷所有記錄并烘焙數據集


$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);

生成的數組將如下所示


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

? ? ? ? )


)

另一種速記方法但不優選是在查詢級別應用聚合方法,例如如果您使用 MySQL,您可以使用group_concat但它有最大字符限制(可調)的限制。


查看完整回答
反對 回復 2023-10-22
  • 1 回答
  • 0 關注
  • 124 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號