php - 选择 MySQL If (ID) 在数组中

标签 php mysql codeigniter

所以我尝试构建一个通知系统(CodeIgniter),而不是通过这个唯一的 ID 将其存储在我的数据库中。现在我在使用“SELECT 查询”时遇到了一些问题。

IMG

这也是存储在“值”行中的数组:

[{"id":0,"user_id":"1","comment":"That's a Nice Video.","posttime":1403523177,"status":1},{"id":1,"user_id":"4","comment":"Nice to see this..!!","posttime":1403590409,"status":1}]

这是我的(非工作)查询:

$query = $this->db->get_where('post_meta',array('status'=>1),in_array('user_id', $id));

想法?

注意:通知将由“user_id”分隔。

最佳答案

您不应在该函数上使用 in_array('user_id', $id),因为它返回 bool 值。

在事件记录页面上:https://ellislab.com/codeigniter/user-guide/database/active_record.html您可以查看 get_where() 函数所需的参数

$query = $this->db->get_where('mytable', array('id' => $id), $limit, $offset);

请注意第三个参数如何采用 $limit,它表示您将收到的数据数量。 (将此字段留空将返回所有数据)。

<小时/>

一些代码示例:

如果您只想获取 status = 1 的数据,请使用以下命令:

$query = $this->db->get_where('post_meta',array('status'=>1));

如果您想获取 status = 1user_id = $id 的数据,请使用以下命令:

$this->db->like('value', '"user_id":"'.$id.'"'); 
$query = $this->db->get_where('post_meta',array('status'=>1));

上面的解决方案不是最好的,但应该可行。 $this->db->like() 函数将创建规则以获取具有 "user_id":"$id"value 行中的数据code> 其中 $id 是您定义的值。

<小时/>

如果我想获取所有通知并根据 ID 对它们进行分组,该怎么办?

我通常会获取所有数据,然后使用 PHP 将它们分组到自己的数组中。我认为这比依赖数据库来做到这一点要便宜(如果我错了,请纠正我)。

所以使用第一个代码:

$query = $this->db->get_where('post_meta',array('status'=>1));

然后使用 foreach() 或任何您认为方便的方式迭代它们。

$data = array();
foreach($query as $k=>$v) {
    // Run a function to get User ID
    $user_id = your_function_here($v->value);

    if(!isset($data[$user_id]))
        $data[$user_id] = array();

    // This is just some example to group them together, you can optimize it to your own liking
    array_push($data[$user_id],$v);
}

your_function_here() 是从数据库的 value 行获取 user_id 的函数。

关于php - 选择 MySQL If (ID) 在数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29155182/

相关文章:

MySQL 获取逗号分隔值

PHP + MSSQL 使用命名参数不是 '?' 的 PDO

php - 代码点火器 | .htaccess 从 url 中删除 index.php

php - MySQL WHERE IN() 和 IN()

php - 重命名上传文件,将新名称发布到数据库

php - CakePHP 3 session 更新

mysql - 从多个表中获取最大的ID并删除重复值

javascript - 来自两个向量的 Highchart 图 : split the vectors?

大型数据库的 MySQL 转储似乎小于原始 MySQL 数据库本身

php - 使用 PHP + CodeIgniter 从 MySQL 数据库生成无序列表