php – SQL连接结果到codeigniter中的对象
发布时间:2020-05-25 09:17:06 所属栏目:PHP 来源:互联网
导读:好的,有点背景, 刚进入codeigniter 不是sql和服务器端脚本的粉丝 我知道加入的是什么 我第一次有一个多对多的数据库 这是因为连接通常具有以下示例作为结果.但我想解析这个,而不必构建代码来忽略重复.这是一个3表连接样本.当我加入更多表时,重复值的问题会增
好的,有点背景, >刚进入codeigniter 这是因为连接通常具有以下示例作为结果.但我想解析这个,而不必构建代码来忽略重复.这是一个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); (编辑:安卓应用网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |