2012-02-06 127 views
6

OK,有點背景的,SQL連接結果爲對象笨

  • 剛剛進笨
  • 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 

有CI中(或純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'] 
    } 
] 

更新:這並不限於此深度的對象/陣列(像中的例子)。它可以更深入(數組中的數組,數組中的對象,數組中的對象,對象中的對象)

回答

7
// 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); 
+0

正是我所需要的。謝謝! – Joseph 2012-02-06 07:24:19

+0

我很高興我能幫到你。 – 2012-02-06 07:26:46