Сергей Петров Сергей Петров - 2 months ago 7x
JSON Question

PHP - REGEX - Remove objects from json by key

I have a little problem with my task. I have a json and I need just one type of them... I need objects just like this:

{"type1":"X","type2": "value2","type3":"value3"}

from json like this

{"alerts":[{"type1":"x","type2": "value2","type3":"value3"}, {"type1":"value1","type2": "value2","type3":"value3"}]}

I just need objects where "TYPE1" is "X", others do not. I think I must use a REGEX, but I do not know nothing about it. Now I'm using the cycle, but the data is a lot and it takes a long time.

Here is my actual loop:

$carray = json_decode($data);
foreach($carray->alerts as $alert){
if($alert->type1 != 'X') { continue; }
// some code

I hope you understand me. Thanks for help!


Well, since you need to filter an array, you should probably use array_filter:

$carray = json_decode($data);
$alerts = array_filter($carray->alerts, function($alert) {
    return $alert->type1 == 'X';
foreach($alerts as $alert) {
    //do something;