CodeIgniter foreach 循环返回值问题

问题描述 投票:0回答:1

我被 CodeIgniter 循环和数组困住了,我想获取每个用户名和 pid 时间。

    function UserStat()
    {       
        $this->db->select('username');      
        $this->db->where('status=','1');
        $query=$this->db->get("user_id");
        $uname=$query->result_array();
        
        foreach($uname as $name)
        {
            $this->db->select('SUM(pid) AS `UserTotalPid`');
            $this->db->like('user',$name['username']);
            $UsrTotalPidInSec['UserTotalPid']=$this->db->get('user_data')->row()->UserTotalPid;
            $data[]['username']=$name['username'];
            $data[]['UsrTotalPidInMin']=floor($UsrTotalPidInSec['UserTotalPid']/60).':'.gmdate('s',$UsrTotalPidInSec['UserTotalPid']);
        
        }
        return $data;
        //print_r($data);
    }
}

我现在得到这个回报

返回输出:

[{"username":"Michle"},{"UsrTotalPidInMin":"1:58"},{"username":"Docker"},{"UsrTotalPidInMin":"0:55"},{"username":"Marchel"},{"UsrTotalPidInMin":"2:34"}]

print_r 输出:

Array ( [0] => Array ( [username] => Michle ) [1] => Array ( [UsrTotalPidInMin] => 1:58 ) [2] => Array ( [username] => Docker ) [3] => Array ( [UsrTotalPidInMin] => 0:55 ) [4] => Array ( [username] => Marchel ) [5] => Array ( [UsrTotalPidInMin] => 2:34 ) )

如果我将 return 或 print 数组放在循环内,我会得到这个

返回输出:

[{"username":"Michle"},{"UsrTotalPidInMin":"1:58"}]

print_r 输出:

Array ( [0] => Array ( [username] => Michle ) [1] => Array ( [UsrTotalPidInMin] => 1:58 ) ) Array ( [0] => Array ( [username] => Michle ) [1] => Array ( [UsrTotalPidInMin] => 1:58 ) [2] => Array ( [username] => Docker ) [3] => Array ( [UsrTotalPidInMin] => 0:55 ) ) Array ( [0] => Array ( [username] => Michle ) [1] => Array ( [UsrTotalPidInMin] => 1:58 ) [2] => Array ( [username] => Docker ) [3] => Array ( [UsrTotalPidInMin] => 0:55 ) [4] => Array ( [username] => Marchel ) [5] => Array ( [UsrTotalPidInMin] => 2:34 ) )

但是我的例外是这样的

返回输出:

[{"username":"Michle","UsrTotalPidInMin":"1:58"},{"username":"Docker","UsrTotalPidInMin":"0:55"},{"username":"Marchel","UsrTotalPidInMin":"2:34"}]

print_r 输出:

Array ( [username] => Michle [UsrTotalPidInMin] => 1:58 ) Array ( [username] => Docker [UsrTotalPidInMin] => 0:55 ) Array ( [username] => Marchel [UsrTotalPidInMin] => 2:34 )

如何解决这个问题?

php arrays codeigniter-3
1个回答
0
投票

感谢您提供实际和预期结果。这很有帮助。

要解决您的阵列问题,您可以更改此部分...

$data[]['username']=$name['username'];
$data[]['UsrTotalPidInMin']=floor($UsrTotalPidInSec['UserTotalPid']/60).':'.gmdate('s',$UsrTotalPidInSec['UserTotalPid']);

对于类似...

$UsrTotalPidInMin = floor($UsrTotalPidInSec['UserTotalPid']/60).':'.gmdate('s',$UsrTotalPidInSec['UserTotalPid']);
$data[] = array('username'=>$name['username'],'UsrTotalPidInMin'=>$UsrTotalPidInMin);

在上面,我把 $UsrTotalPidInMin 拿出来作为单独的语句,以使 $data[] 语句更容易阅读。

© www.soinside.com 2019 - 2024. All rights reserved.