2012-02-06 66 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