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;

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

报告相同问题?

悬赏问题

  • ¥33 找熟练码农写段Pyhthon程序
  • ¥100 怎么让数据库字段自动更新
  • ¥15 antv g6 力导向图布局
  • ¥15 quartz框架,No record found for selection of Trigger with key
  • ¥15 锅炉建模+优化算法,遗传算法优化锅炉燃烧模型,ls-svm会搞,后面的智能算法不会
  • ¥20 MATLAB多目标优化问题求解
  • ¥15 windows2003服务器按你VPN教程设置后,本地win10如何连接?
  • ¥15 求一阶微分方程的幂级数
  • ¥15 关于#线性回归#的问题:【统计】回归系数要转化为相关系数才能进行Fisher' Z转化吗(相关搜索:回归模型)
  • ¥100 使用matlab解决含分段变量的优化问题