2013-05-21 60 views
0

這可能非常不雅,但這是我的問題。向PHP中的對象屬性添加迭代

我有對象的這樣一個返回數組..

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 ; 

如果我已經解釋得很好,誰能幫到忙?

謝謝!

回答

0

我認爲你應該使用動態變量名的創作,這是很好說明如下:

Dynamic variable names in PHP

所以在你的代碼應該有類似的東西:

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

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

+0

完美,謝謝你。我只需要在下面添加括號......'echo $ count [「count_ $ role $ i」] - > {$ role $ n};' – bencarter78