문제

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?

도움이 되었습니까?

해결책

The simplest way I see to do that is to use a foreach:

$myStdClass = /* ... */;
$a = '';

foreach ($myStdClass as $key => $value) {
    if ($value) {
        $a .= $key;
    }
}

다른 팁

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" 
<?
$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

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top