PHP remove an element from an array with objects by property name

I have this json Format that is my final response, when i get it from an API it only has a property Name. I get this using json_decoe
apiErrors[
{
PropertyName: "Name1",
DisplayName: "Name1",
Step: "Step1
},
PropertyName: "Name2",
DisplayName: "Name2",
Step: "Step2
}
]
I want to remove the items with "Step2" on the Step property.
in PHP I Iterate using a foreach and add the display and step properties
$apiErrors = json_decode(curl_exec($ch));
foreach ($apiErrors as $value) {
if ($value->PropertyName == "Name1") {
$value->DisplayName = 'Name1';
$value->Step = 'Step1';
}
if ($value->PropertyName == "Name2") {
$value->DisplayName = 'Name2';
$value->Step = 'Step2';
}
}
I tried to do this
if (($key = array_search("Step2", $apiErrors)) !== false) {
unset($apiErrors[$key]);
}
but it doesn't remove anything
Answer
Solution:
Simple filtering will do the job:
$apiErrors = array_filter(
$apiErrors,
function ($v) { return 'Step2' !== $v->Step; }
);
Answer
Solution:
I know it's confusing at first, but PHP doesn't automatically update the value if you use , because it makes its own local variables. You need to specify yourself with an
&
in front of the$value
, like this:foreach ($apiErrors as &$value) {
. This will make sure that the value in the array actually changes.
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: 403 this action is unauthorized.
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.