SQL join results into an object in codeigniter

前端 未结 1 1064
囚心锁ツ
囚心锁ツ 2021-01-05 10:55

ok, a bit of background,

  • just into codeigniter
  • not a fan of sql and server-side scripts
  • i know what joins are
  • i have a many-to-many
相关标签:
1条回答
  • 2021-01-05 11:36
    // 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 讨论(0)
提交回复
热议问题