第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號(hào)安全,請(qǐng)及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問題,去搜搜看,總會(huì)有你想問的

MySQL選擇多維?

MySQL選擇多維?

PHP
寶慕林4294392 2021-07-02 14:00:44
我想從我的數(shù)據(jù)庫中選擇所有帖子及其附件。這是帶有虛擬數(shù)據(jù)的結(jié)構(gòu):帖子表id       | post          | userId   | ---------|---------------|----------|1        | "hello"       |  1       |2        | "world"       |  1       |3        | "ouch"        |  2       |4        | "test"        |  1       |附件表id       | postId        | fileName |  time    | ---------|---------------|----------|----------|1        | 1             |"hey.jpg" |        0 |2        | 1             |"test.png"| 53252354 |3        | 2             |"asd.png" |        0 |4        | 4             |"asd2.png"|        0 |到目前為止,我的代碼看起來像這樣,但我并沒有真正得到我想要的。$qry = $db->prepare('SELECT p.id     , p.post     , p.userId     , att.fileName     , att.time  FROM posts p  LEFT   JOIN attachments att     ON att.postId = p.id');$qry->execute();$postsArray = $qry->fetchAll(PDO::FETCH_ASSOC);我想要這樣的東西:[{'id': 1,'post': 'hello','userId': 1,'attachments': [{'fileName': 'hey.jpg', 'time:' 0}, ... ]}, ... ]我怎么能做到這一點(diǎn)?
查看完整描述

2 回答

?
函數(shù)式編程

TA貢獻(xiàn)1807條經(jīng)驗(yàn) 獲得超9個(gè)贊

您的查詢將為您提供所需結(jié)果的正確數(shù)據(jù),您可以在 PHP 中進(jìn)行后處理以獲得所需的格式:


foreach ($postArray as $post) {

    $fixed_part = array('id' => $post['id'], 'post' => $post['post'], 'userId' => $post['userId']);

    $key = serialize($fixed_part);

    if (!isset($out[$key])) $out[$key] = $fixed_part;

    $out[$key]['attachments'][] = array('fileName' => $post['fileName'], 'time' => $post['time']);

}

$out = array_values($out);

echo json_encode($out, JSON_PRETTY_PRINT);

輸出太長無法發(fā)布,但可以在此演示中看到。查詢結(jié)果可以在dbfiddle看到


查看完整回答
反對(duì) 回復(fù) 2021-07-09
  • 2 回答
  • 0 關(guān)注
  • 187 瀏覽

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)