简体   繁体   中英

Remove items from an array where they match a certain criteria in PHP

I have an array of products and i need to remove all of them which have a reference to webinar

The PHP version I am using is 5.2.9

$category->products

example:

    [6] => stdClass Object
            (
                [pageName] => another_title_webinar
                [title] => Another Webinar Title
            )

        [7] => stdClass Object
            (
                [pageName] => support_webinar
                [title] => Support Webinar
            )
[8] => stdClass Object
            (
                [pageName] => support
                [title] => Support
            )

In this case number 8 would be left but the other two would be stripped...

Could anyone help?

Check out array_filter() . Assuming you run PHP 5.3+, this would do the trick:

$this->categories = array_filter($this->categories, function ($obj) {
    if (stripos($obj->title, 'webinar') !== false) {
        return false;
    }

    return true;
});

For PHP 5.2:

function filterCategories($obj)
{
    if (stripos($obj->title, 'webinar') !== false) {
        return false;
    }

    return true;
}

$this->categories = array_filter($this->categories, 'filterCategories');

You can try

$category->products = array_filter($category->products, function ($v) {
    return stripos($v->title, "webinar") === false;
});

Simple Online Demo

You could use the array_filter method. http://php.net/manual/en/function.array-filter.php

function stripWebinar($el) {
  return (substr_count($el->title, 'Webinar')!=0);
}

array_filter($category->products, "stripWebinar")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM