doulu1945 2013-05-21 14:51
浏览 61
已采纳

在PHP中添加迭代到对象属性

This is likely to be very inelegant however this is my problem.

I have a returned array of objects like this..

Array ( 
    [count_assessor0] => stdClass Object ( [assessor0] => 91 ) 
    [count_assessor1] => stdClass Object ( [assessor1] => 3 ) 
    [count_assessor2] => stdClass Object ( [assessor2] => 5 ) 
    [count_assessor3] => stdClass Object ( [assessor3] => 24 ) 
    [count_verifier0] => stdClass Object ( [verifier0] => 91 ) 
    [count_verifier1] => stdClass Object ( [verifier1] => 3 ) 
    [count_verifier2] => stdClass Object ( [verifier2] => 5 ) 
    [count_verifier3] => stdClass Object ( [verifier3] => 24 ) 
)

Ok, so as you can see each array and property have a numerical suffix. What I want to do is use these suffixes in a foreach loop below however when it comes to adding $n to the objects property I get an error as it doesn't 'add' the suffix on to $role.

$options = array('Yes - Qualified', 'Yes - Not Qualified', 'No - Working Towards', 'No - Not Working Towards');
$roles = array('assessor' => $options, 'verifier' => $options, 'teaching_status' => $options, 'coaching_status' => $options);

$i = 0 ;

foreach($roles as $role => $options){
    echo ucwords($role);
    $n = 0 ;
    foreach($options as $option) {
        echo $option ;
        echo $count["count_$role$i"]->$role$n;
        $n++ ;
        $i++ ;
    endforeach ;
    unset($n) ;
endforeach ;

If I have explained this well enough can anyone help?

Thanks!

  • 写回答

1条回答 默认 最新

  • dongpao9437 2013-05-21 15:08
    关注

    I think You should make use of dynamic variable name creation, it is well described here:

    Dynamic variable names in PHP

    So in You code there should be something like that:

    $property = ${$role.$n};

    echo $count["count_$role$i"]->$property;

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?