将数组计数传递给变量

时间:2018-10-08 16:08:00

标签: php arrays count

我想我已经接近我的代码了,但是我正试图从提供的数组中获取count() ...总用户和操作系统

        $users = array();
        if ($results = $dbh->runQuery($sql)) {

foreach ($results as $key=>$row){
        $users[$row['user_id']][] = array('user_id'=>$row['user_id'],
        'email' => $row['email'],
        'last_login' => $row['last_login'],
        'fname' => $row['fname'],
        'lname' => $row['lname'], 
        'role_id' => $row['role_id'],
        'role_name' => $row['role_name'],
        'os_d_token' => $row['os'],
        'roid_d_token' => $row['roid'],
        'p_name' => $row['p_name']);
            }
        }

获取用户总数

    $user_cnt = count($row['user_id']);

获取使用操作系统的用户总数

    $total_os = '';
    if($row['os'] != null || '-1') {

        $total_os = count($row['os']);

    }

1 个答案:

答案 0 :(得分:2)

count不会为您保留计数器。它立即返回数组中的项目数。由于您已经在循环,请设置计数器变量:

$total = 0;
$total_os = 0;
foreach ($results as $key=>$row) {
    $total++;
    if ($row['os'] != null || $row['os'] != '-1') {
        $total_os++;
    }
    ...
}