Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialRrR KkK
2,363 PointsPHP Stdclass Object
Hello Teachers,
I have a question I am kinda confused and not getting the right results
- I have an object(stdClass) like this
object(stdClass)#369 (17) { ["title"]=> string(25) "I am title 1" ["someproperty1"]=> string(0) "" ["someproperty2"]=> string(0) "" ["section"]=> string(8) "projects" ["someproperty3"]=> string(0) "" ["someproperty4"]=> string(0) "" ["someproperty5"]=> string(0) "" ["someproperty6"]=> ...etc. }
object(stdClass)#441 (17) { ["title"]=> string(25) "I am title 2" ["someproperty1"]=> string(0) "" ["someproperty2"]=> string(0) "" ["section"]=> string(8) "projects" ["someproperty3"]=> string(0) "" ["someproperty4"]=> string(0) "" ["someproperty5"]=> string(0) "" ["someproperty6"]=> ...etc. }
If you notice in the stdClass there is a property called "section" it has a value of a string and this string could be projects, companies, universities...etc.
What I am trying to do is
foreach($this->results as $result) {
$projectItem = NULL;
/* accessing the section property in the stdClass and if it is equals to projects count how many objects its section property is equal to projects */
if($result->section == "projects"){
$projectItem = $result;
echo "<pre>";
echo count($result);
}
}
What I wanna do is count every object where its section property equals a specific value I could achieve getting a result of 1 in each result but it is not counting so how can I do this please help and thanks in advance :)
1 Answer
Henrik Hansen
23,176 PointsIf you only want a simple counter for each time you find the right value, the initialize a variable before the foreach loop and set it to zero ($i = 0). The increment it inside the if statement, and after the loop finished you have counted each time the loop found your value.
// Initialize counter
$i = 0;
// Do the loop
foreach( $this->result as $result ){
if ($result->section == $value) {
// increment counter
$i++;
}
} // end foreach
echo( $i );