John Davidson

php - unset std object whole key based condition check

0 comments
Message:


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
)

}


My Answer:
stdClass Object
(
[0] => stdClass Object
(
[id] => 1
[name] => John
[status] => Active
)

[1] => stdClass Object
(
[id] => 2
[name] => Jane
[status] => Inactive
)

[2] => stdClass Object
(
[id] => 3
[name] => Bob
[status] => Active
)
)

To filter the data and get only the objects with status = Active, you can use the following code:

php
foreach ($newresults as $key => $result) {
if ($result->status !== 'Active') {
unset($newresults[$key]);
}
}

print_r($newresults);


This code loops through each object in the `$newresults` array and checks if the `status` property is not equal to 'Active'. If it is not, the object is removed from the array using `unset()`. Finally, the filtered array is printed using `print_r()`.

Rate this post

5 of 5 based on 1654 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us