Reputation: 1033
Following is the output of my stdClass object:
stdClass Object (
[all] => 0
[book] => 0
[title] => 1
[author] => 1
[content] => 0
[source] => 0
)
I want to store the elements that have a value 1
in a variable.
Suppose, in the above example, I want to store $a='author' . 'title'
. Is this possible by using foreach
or any other tidy approach, instead of manually checking for each whether they have a value of 1
or not and then storing them?
Upvotes: 0
Views: 837
Reputation: 2735
One-liner solution:
$c = new stdClass();
$c->all = 0;
$c->book = 0;
$c->title = 1;
$c->author = 1;
$c->content = 0;
$c->source = 0;
$a = implode(',', array_keys( array_filter( (array)$c) ) );
var_dump($a);
Would yield
string(12) "title,author"
Upvotes: 1
Reputation: 29874
<?
$result = '';
foreach($your_stdclass as $key => $value) {
if($value == '1') {
$result .= $key;
}
}
echo $result;
?>
that appears to be what you ask altough i dont know how that makes sense
Upvotes: 0
Reputation: 364
The simplest way I see to do that is to use a foreach:
$myStdClass = /* ... */;
$a = '';
foreach ($myStdClass as $key => $value) {
if ($value) {
$a .= $key;
}
}
Upvotes: 1