簡體   English   中英

選擇MySQL If(ID)在數組中

[英]Select MySQL If (ID) In Array

因此,我嘗試構建一個通知系統(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) ,因為它返回布爾值。

在活動記錄頁面上: https : get_where()您可以看一下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行中獲取數據,其中$ 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的函數。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM