foreach循环只显示codeigniter中的最后一条记录,并获取5分钟后记录的活动记录

时间:2018-06-05 11:50:51

标签: php codeigniter

大家好我想在codeigniter中获取活动会话用户。所以我将所有会话存储在数据库和名称为ci_sessions的表名中,我从ci_sessions表中获取用户数据,我试图通过foreach从数据中获取user_name但我只是最后一个活跃的用户。

这是我的代码:

<?php
$query = $this->db->query('SELECT * FROM ci_sessions');

foreach ($query->result() as $row) {
    $session_data = $row->data;

    $return_data = array();  // array where you put your "BLOB" resolved data

    $offset = 0;
    while ($offset < strlen($session_data)) 
    {
        if (!strstr(substr($session_data, $offset), "|")) 
        {
            throw new Exception("invalid data, remaining: " . substr($session_data, $offset));
        }
        $pos = strpos($session_data, "|", $offset);
        $num = $pos - $offset;
        $varname = substr($session_data, $offset, $num);
        $offset += $num + 1;
        $data = unserialize(substr($session_data, $offset));
        $return_data[$varname] = $data;  
        $offset += strlen(serialize($data));
    }    
}
echo $return_data['user_name'];

?>

任何人都可以在我错误的地方帮助我。

提前致谢。

1 个答案:

答案 0 :(得分:2)

你做的一个小错误

<?php
$query = $this->db->query('SELECT * FROM ci_sessions');
$return_data = array();  // array where you put your "BLOB" resolved data
foreach ($query->result() as $row) {
   $session_data = $row->data;

   $offset = 0;
   while ($offset < strlen($session_data)) 
    {
       if (!strstr(substr($session_data, $offset), "|")) 
        {
          throw new Exception("invalid data, remaining: " . substr($session_data, $offset));
        }
          $pos = strpos($session_data, "|", $offset);
          $num = $pos - $offset;
          $varname = substr($session_data, $offset, $num);
          $offset += $num + 1;
          $data = unserialize(substr($session_data, $offset));
          $return_data[$varname][] = $data;  
          $offset += strlen(serialize($data));
      }

      }
     var_dump( $return_data['user_name'][0] );

     foreach($return_data['user_name'] as $onesession) {
          echo $onesession;
          echo '<br>';
     }

?>

$ return_data = array();我把它移出了foreach循环