在我的Users控制器中,通过查询“Forms”表并将其存储在数组中,我找到了用户创建的表单数。但是如何在视图文件中使用数组变量。

通常,我会使用set函数在控制器中设置变量,并在视图文件中使用它。但是如何在控制器中设置一个数组呢?我得到控制器中的值(做了一个回声)。

我的控制器代码是:

function users(){

   $this->set('users',$this->User->find('all'));
   $users=$this->User->find('all');
   foreach($users as $user):

     $id=$user['User']['id'];
     $userFormCount[$id]=$this->Form->find('count',array('conditions'=>array('Form.created_by'=>$user['User']['id'])));
     $userFormCount[$id]=$this->Form->find('count',array('conditions'=>array('Form.created_by'=>$user['User']['id'])));      
     echo "users : ".$id."  ".$userFormCount[$id];

   endforeach;
}

我的观点文件:

<?php foreach($users as $user):?>

   <tr>
  <td class="people_profile">

         <a href="/users/angeline"><?php echo $user['User']['name'];?></a>
      </td>

     <td>
    <?php 
    $id=$user['User']['id'];
    echo $userFormCount[$id]." ";?>forms,   //need the array value here.
    0 reports,
    0 badges
  </td>
 </tr>
<?php endforeach;?>

由于我已将值存储在控制器中的变量$ userFormCount中,因此我没有在视图文件中获取该值。但是如何设置和获取数组值?

有帮助吗?

解决方案

首先,你应该避免重复你的函数调用。

您的功能的前两行可以替换为:

$users=$this->User->find('all');
$this->set('users', $users);

接下来,您可以在将对象传递给视图之前更改它,并将要计算的属性添加到该对象。

function users(){

    $users=$this->User->find('all');

    // notice the & here
    foreach($users as & $user):

       // you are repeating the same line here as well, that's not necessary
       $user['User']['custom_field'] = $this->Form->find('count', 
           array('conditions'=>array('Form.created_by'=>$user['User']['id'])));
    endforeach;

    $this->set('users', $users);
}

然后您可以在视图中使用它,就像从数据库中获取的任何其他字段一样。为了进一步改进它,您可能需要考虑将此代码移动到 User 模型中的 afterFind 回调,至少如果此自定义值被多次使用一次。

其他提示

您已经知道如何设置数组值: - )

在此代码中,您将设置数组'users'

$this->set('users',$this->User->find('all'));

所以你可以为另一个数组做同样的事情:

$this->set('userFormCount',$userFormCount);

...并以与用户变量相同的方式阅读。

但请查看RaYell的答案,因为它解释了如何使您当前的代码更好。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top