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 chaquopy python 安卓
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 有没有帮写代码做实验仿真的
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥30 vmware exsi重置后登不上
  • ¥15 易盾点选的cb参数怎么解啊
  • ¥15 MATLAB运行显示错误,如何解决?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容
  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题