SQL连接结果成为codeigniter中的对象

Jos*_*eph 6 php mysql json 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
Run Code Online (Sandbox Code Playgroud)

在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']
    }
]
Run Code Online (Sandbox Code Playgroud)

更新:这不限于此深度的对象/数组(如示例中所示).它可以更深入(数组中的数组,对象中的数组,数组中的对象,对象中的对象)

J. *_*uni 8

// 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);
Run Code Online (Sandbox Code Playgroud)