5

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?

Andy
  • 2,991
  • 9
  • 43
  • 62

3 Answers3

5

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');
smottt
  • 3,272
  • 11
  • 37
  • 44
  • Your code is wrong you are making `webinar` haystack instead of needle see http://eval.in/4811 – Baba Dec 17 '12 at 10:30
  • 1
    Early morning hours ugh.. sorry about that! @Baba, thanks for the correction. :) – smottt Dec 17 '12 at 10:34
  • Then you just need to move the anonymous function to a normal function and use it's name as callback. As Hugo below already mentioned. And I also edited mine. ;) – smottt Dec 17 '12 at 10:40
3

You can try

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

Simple Online Demo

Baba
  • 94,024
  • 28
  • 166
  • 217
  • Andy upgrade that was last supported `26-Feb-2009` ...... see http://php.net/ChangeLog-5.php ... you are more problems than you think .... – Baba Dec 17 '12 at 10:41
  • Thanks for the eval.in link...well worth bookmarking unfortunately i am using 5.2.9 – Andy Dec 17 '12 at 10:43
1

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")
Hugo Delsing
  • 13,803
  • 5
  • 45
  • 72