1

I am pulling elements from a standard class object into an assoc array like so:

$array = $subjects;
foreach ( $array as $subject ) {

    foreach ( $subject as $prop => $val ) {
        if ( $val !== '' ) {
         echo $prop . ' = ' . $val;
         echo "<br>";
        }
    }
}

I get the result I expect from above, except what I'd like to do is echo out individual values into a table.

When I do this: echo $subject['day1']; I get this: "Cannot use object of type stdClass as array."

Where am I going wrong? Thanks in advance.

2

2 Answers 2

1

If it's using StdClass you'll need to do this:

$subject->day1

If you want to convert it to an array, have a look at this question: php stdClass to array

Sign up to request clarification or add additional context in comments.

1 Comment

This worked. $subject->day1. Is it possible to append an index like this: $subject->day.$x ?
0

You are trying to iterate over the $array and $array is still an object. Use this:

    $vars = get_object_vars($subjects);

to get assoc. array from the object $subjects. Then go:

foreach ($vars as $name => $value) {
    echo $name . "=" . $value;
    echo "<br>";
}

10 Comments

get_object _vars gives an array of 0.
Then your object is not well defined. Tell me what do you get if you type this: print "<pre>"; print_r($subjects); print "</pre>";
That means that $subjects is already an array, not an object.
Ok, use this: $vars = get_object_vars($subjects[0]); to get assoc. array from the array $subjects first element. Then go: foreach ($vars as $name => $value) { echo $name . "=" . $value; echo "<br>"; }
when I do this: echo $subject->day11; I get expected result. I want to put all values in a table. How to loop through values? If i add an index like this: $x ='11'; echo $subject->day.$x; $x++; will not work. What I want is efficient way to get to each value. Driving me mad.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.