trying to filter data from std object to get result only with status = Active
here is my data =
$newresults =
array {
[1] => stdClass Object
(
[id] => 30508
[status] => Active
)
[2] => stdClass Object
(
[id] => 30509
[status] => InActive
)
[3] => stdClass Object
(
[id] => 30510
[status] => Active
)
}
in foreach loop i need to get new array of std object with status = active only
so far i am trying to do this with
foreach ($newresults as $key => $value) {
if($value->status == 'Inactive')
unset($newresults[$key]);
}
$newresults[]=$value;
}
return $newresults;
thanks in advance i am sure i can do it this way but i might be doing mistake somewhere
expected output =
array {
[1] => stdClass Object
(
[id] => 30508
[status] => Active
)
[2] => stdClass Object
(
[id] => 30510
[status] => Active
)
}
CodePudding user response:
You could just use array_filter
:
$newresults = array_filter($newresults, function ($v) { return $v->status == 'Active'; });
print_r($newresults);
Output:
Array
(
[1] => stdClass Object
(
[id] => 30508
[status] => Active
)
[3] => stdClass Object
(
[id] => 30510
[status] => Active
)
)
If you want the array to be re-indexed starting at 0, just use array_values
on the result.
CodePudding user response:
That should work where you just remove those "Inactive" ones.
foreach ($newresults as $key => $value) {
if ($value->status == 'Inactive') {
unset($newresults[$key]);
}
}