資料庫查詢結果構建多維陣列解決辦法

來源:互聯網
上載者:User
資料庫查詢結果構建多維陣列
我想將前面資料庫查詢出來的結果構建一個多維陣列,資料庫查詢出來的第一個結果對應第一層嵌套,第二個結果對應第二層嵌套,如何做,事先聲明我是菜鳥,請多指點

// 查詢變數

$sql1 = "select remark,name from arp_careset where typegroup ='dissect-position' order by id";
$rs1 = mysql_query($sql1);

while($r1 = mysql_fetch_assoc($rs1))
{ echo $r1['name'];

$sql = "select group_concat(name) as name from arp_careset where typegroup <>'dissect-position' and typegroup like '%".$r1["remark"]."%' order by id";
$rs = mysql_query($sql);

while($r = mysql_fetch_array($rs))
{ $ar = explode(',', $r['name']);
echo join(' ', $ar);
} }
//構建數組

$mem = array(
array
(
lang_show(''),
array
(
// 嵌套開始
array(
lang_show('account_manager'),
//第二層嵌套
array(
'group_list.php,1',
)
//第二層嵌套結束
),
// 嵌套結束
)
),
);

------解決方案--------------------
你的資料群組織給你的讀出帶來了很多不便
這樣寫
$rs = mysql_query("select name, SUBSTRING_INDEX(typegroup,'-',-1) as secondary, remark from arp_careset where SUBSTRING_INDEX(typegroup,'-',1)='dissect'");
while($r = mysql_fetch_assoc($rs)) {
echo $r['name']. '
';
$rs1 = mysql_query("select name, SUBSTRING_INDEX(typegroup,'-',-1) as secondary, remark from arp_careset where SUBSTRING_INDEX(typegroup,'-',1)='$r[secondary]' and SUBSTRING_INDEX(typegroup,'-',-1) = '$r[remark]'");
while($r = mysql_fetch_assoc($rs1)) {
echo $r['name'] . ' ';
}
echo '
';
}


體表
營養狀況 分泌物 被毛 皮膚 眼/眼眶 四肢/尾巴 乳腺 外生殖器 肛門
淋巴結
腋窩淋巴結 頸部淋巴結 腹股溝淋巴結 肺部淋巴結 腸系淋巴結
頭頸部
眼瞼/角膜/瞳孔 牙齒/牙齦 耳 鼻 腦膜/全腦 顱骨 唾液腺 食管 氣管 甲狀腺
胸部
胸壁 橫膈/縱膈 心臟 主動脈弓 肺及支氣管
腹部
腹腔 腸系膜 脾臟 胰 腎臟

------解決方案--------------------
為什麼說資料群組織的不好呢?
主分組 typegroup 包含了兩個類別資訊
而按“鄰接列表演算法”應該只包含一個類別資訊
從你的資料上看,需要通過 typegroup、remark 兩個欄位來唯一確認一個表象的歸屬
這實際上就是“鄰接列表演算法”了

雖然現在可以用 SUBSTRING_INDEX 函數去拆分 typegroup 來得到類別資訊
但 SUBSTRING_INDEX 函數是 mysql 專有的。如果因為某些原因,以後更換了資料庫系統,那代碼修改量就太大了

雖然你可以將拆分的工作交給 php 完成,但眾多的 like 將降低查詢效率
程式也顯得比較臃腫
------解決方案--------------------
建立多維陣列示意
$res = array(); //這是結果數組
$rs = mysql_query("select name, SUBSTRING_INDEX(typegroup,'-',-1) as secondary, remark from arp_careset where SUBSTRING_INDEX(typegroup,'-',1)='dissect'");
while($r = mysql_fetch_assoc($rs)) {
$tmp = array(); //初始化一個臨時數組
$rs1 = mysql_query("select name, SUBSTRING_INDEX(typegroup,'-',-1) as secondary, remark from arp_careset where SUBSTRING_INDEX(typegroup,'-',1)='$r[secondary]' and SUBSTRING_INDEX(typegroup,'-',-1) = '$r[remark]'");
  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.