Monday, March 30, 2009

Fatal error: Cannot use object of type stdClass as array...

While programming, I was stuck in this bug.
Fatal error: Cannot use object of type stdClass as array in C:\xampp\htdocs\redtaglogo2\members\temp3.php on line 24

I immediately check the var_dump output of the array and I got:
array(3) { [1]=> object(stdClass)#14 (6) { ["id"]=> string(1) "1" ["parent_id"]=> string(1) "0" ["title"]=> string(8) "Artistic" ["nleft"]=> string(1) "1" ["nright"]=> string(2) "28" ["nlevel"]=> string(1) "1" } [5]=> object(stdClass)#13 (6) { ["id"]=> string(1) "5" ["parent_id"]=> string(1) "1" ["title"]=> string(7) "Objects" ["nleft"]=> string(2) "20" ["nright"]=> string(2) "27" ["nlevel"]=> string(1) "2" } [6]=> object(stdClass)#12 (6) { ["id"]=> string(1) "6" ["parent_id"]=> string(1) "5" ["title"]=> string(6) "People" ["nleft"]=> string(2) "23" ["nright"]=> string(2) "24" ["nlevel"]=> string(1) "3" } }

Which looks correct and I have something for my array. The code that was producing the error was:
for ($i=0; $i <>
echo $path[$i][0];
}

I then tried to get it like an object:
for ($i=0; $i < sizeof($path); $i++) {
echo $path[$i]->title;
}

It returned me the wrong results!

I finally solved the problem using foreach:
foreach ($path as $stdObject) {
echo $stdObject->title . "
";
}


Viola