将总数添加到数组中

时间:2012-05-10 19:12:37

标签: php cakephp php-5.3

以下算法将用户添加到公司阵列。我想为任何给定的公司添加总共用户。我该怎么做呢

public function all_company_information($id = null){
        $arrCompany = array();
        $arrCompany['company']= array();
        $arrData = array();
        $this->autoRender = false;
        $this->loadModel("User");
        $users = $this->User->find('all');
        foreach($users as $k => $user){


                if(!in_array($user['User']['company_id'], $arrCompany['company'])){

                    $arrCompany['company'][$user['User']['company_id']][] = $user;

                }else{

                $arrCompany['company'][$user['User']['company_id']][] = $user;

                }

        }

    }

1 个答案:

答案 0 :(得分:1)

在公司模型上查找,然后您可以轻松获得用户数。

$results = $this->Company->find('all');
foreach($results as $k => $company) {
    $results[$k]['Company']['user_count'] = count($company['User']);
}

这些方面的东西。返回的结果将是Company个记录的数组,每个Company记录将在User键中包含相关用户记录的列表。