Search code examples
phparraysmultidimensional-arrayfilterpartial-matches

Keep only rows of a 2d array if a comma-separated column value contains a specified value


I have the following multidimensional array.

$arr = array(
    0 => array(
        'id' => 1,
        'title' => 'title1',
        'url' => 'http://www.foo.bar/',
        'blurb' => 'blurb1',
        'custodian' => 'custodia1',
        'tags' => 'tag1',
        'active' => 'Y',
    ),
    1 => array(
        'id' => '2',
        'title' => 'title2',
        'url' => 'http://www.foo.bar/',
        'blurb' => 'blurb2',
        'custodian' => 'custodia2',
        'tags' => 'tag1,tag2',
        'active' => 'Y',
    ),
    2 => array(
        'id' => '3',
        'title' => 'title3',
        'url' => 'http://www.foo.bar/',
        'blurb' => 'blurb3',
        'custodian' => 'custodia3',
        'tags' => 'tag1,tag2,tag3',
        'active' => 'Y',
    ),
);

I need to filter the array so that only the arrays with "tag2" in the tags value are displayed.

I've looked at array_filter but just can't get my head around it.

Here is my attempt but it doesn't work at all. not sure what I'm doing wrong.

$filterArr = array_filter($arr, function($tag) {

   return ($tag['tags'] == 'tag2');

});

Solution

  • The simplest way is to use foreach loop and in the body of loop check for 'tag2'

    If you need to delete all rows without tag2 in tags you can use next loop:

    foreach ($arr as $key => $value) {
        if (!preg_match('/\btag2\b/',$value['tags'])) {
            unset($arr[$key]);
        }
    }