Codeigniter foreach循环返回值问题

时间:2019-06-30 10:33:23

标签: php arrays codeigniter-3

全部 我与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 )

帮我如何解决这个问题,T.I.A

1 个答案:

答案 0 :(得分: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 []语句更易于阅读。