Frage

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!

War es hilfreich?

Lösung

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;

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top