Search code examples
phparraysmultidimensional-arrayfilteringarray-filter

Keep rows in a multidimensional array which contain a specific substring


I have the follow API output, I basicly want to grab the member ids when the field relative contains 'minutes' how can I do this with an array filter?

[
    'members' => [ 
        239 => ['relative' => '21 minutes ago'],
        941591 => ['relative' => '5 hours ago'],        
        4178 => ['relative' => '59 minutes ago'],       
        78 => ['relative' => '2 hours ago']
    ]
]       

(not sure on the correct terms) but "relative" is a header/field name below the member ids, and the field relative contains the values like: "59 minutes ago"

I know I can get my answer by looping through all members and checking the field, but I prefer not to do it this way


Solution

  • Extract the relative column and grep for ones that contain minutes:

    $result = preg_grep('/minutes/', array_column($array['members'], 'relative'));
    

    Or filter:

    $result = array_filter($array['members'],
                           function($v) {
                               return strpos($v['relative'], 'minutes') !== false;
                           });
    

    Then just get the keys:

    $ids = array_keys($result);