簡體   English   中英

SQL連接結果成為codeigniter中的對象

[英]SQL join results into an object in codeigniter

好的,有點背景,

  • 剛進入codeigniter
  • 不是sql和服務器端腳本的粉絲
  • 我知道加入的是什么
  • 我第一次有一個多對多的數據庫

這是因為連接通常具有以下示例作為結果。 但我想解析這個,而不必構建代碼來忽略重復。 這是一個3表連接樣本。 當我加入更多表時,重復值的問題會增加:

table1.authorid    table1.authorname    table2.books     table3.favorited
       1                 john           john's book 1        jean
       1                 john           john's book 1        joe
       1                 john           john's book 2        ken
       1                 john           john's book 2        mark
       2                 mark           mark's book 1        alice
       2                 mark           mark's book 1        ted
       2                 mark           mark's book 2        sarah
       2                 mark           mark's book 2        denise

在codeigniter(或普通PHP)中是否有一種方法可以獲取此數組形式並將其轉換為類似json(並像json一樣解析)

$result = [
    {
        'authorid':1,
        'authorname':'john',
        'books':['john's book1','john's book2'],
        'favorited':['jean','joe','ken','mark']
    },
    {
        'authorid':2,
        'authorname':'mark',
        'books':['mark's book1','mark's book2'],
        'favorited':['alice','ted','sarah','denise']
    }
]

更新 :這不限於此深度的對象/數組(如示例中所示)。 它可以更深入(數組中的數組,對象中的數組,數組中的對象,對象中的對象)

// first, we need the SQL results in the $result_array variable
$sql = 'SELECT ...';  // your SQL command
$result_array = $this->db->query($sql)->result_array();  // codeigniter code

// here the real answer begins
$result = array();

foreach ($result_array as $row)
{
    if (!isset($result[$row['authorid']])
    {
        $author = new StdClass();
        $author->authorid = $row['authorid'];
        $author->authorname = $row['authorname'];
        $author->books = array($row['books']);
        $author->favorited = array($row['favorited']);
        $result[$row['authorid']] = $author;
    }
    else
    {
        if (!in_array($row['books'], $result[$row['authorid']]->books))
        {
            $result[$row['authorid']]->books[] = $row['books'];
        }
        if (!in_array($row['favorited'], $result[$row['authorid']]->favorited))
        {
            $result[$row['authorid']]->favorited[] = $row['favorited'];
        }
    }
}

$result = array_values($result);
echo json_encode($result);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM