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

时间:2013-05-21 14:51:37

标签: php arrays iteration arrayobject

这可能非常不优雅,但这是我的问题。

我有一个像这样返回的对象数组..

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 ) 
)

好的,因为您可以看到每个数组和属性都有一个数字后缀。我想要做的是在下面的foreach循环中使用这些后缀,但是当它向对象属性添加$ n时,我得到一个错误,因为它没有将后缀“添加”到$ 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 ;

如果我已经解释得这么好,任何人都可以帮忙吗?

谢谢!

1 个答案:

答案 0 :(得分:0)

我认为你应该使用动态变量名创建,这里有很好的描述:

Dynamic variable names in PHP

所以在你的代码中应该有类似的东西:

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

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