【问题标题】:Remove items from an array where they match a certain criteria in PHP从数组中删除与 PHP 中的特定条件匹配的项目
【发布时间】:2012-12-04 10:27:22
【问题描述】:

我有一系列产品,我需要删除所有引用网络研讨会的产品

我使用的PHP版本是5.2.9

$category->products

示例:

    [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
            )

在这种情况下,数字 8 将被保留,但其他两个将被剥离...

有人可以帮忙吗?

【问题讨论】:

  • 看起来像 array_filter() 的一个案例,带有一个回调来测试对象页面中的“网络研讨会”

标签: php arrays preg-match unset


【解决方案1】:

查看array_filter()。假设您运行 PHP 5.3+,这可以解决问题:

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

    return true;
});

对于 PHP 5.2:

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

    return true;
}

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

【讨论】:

  • 您的代码错误您正在制作webinar haystack 而不是针请参阅eval.in/4811
  • 凌晨时分啊……抱歉! @Baba,感谢您的更正。 :)
  • 那么你只需要将匿名函数移动到一个普通函数中,并使用它的名字作为回调。正如下面的雨果已经提到的。我也编辑了我的。 ;)
【解决方案2】:

您可以使用 array_filter 方法。 http://php.net/manual/en/function.array-filter.php

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

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

【讨论】:

    【解决方案3】:

    你可以试试

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

    Simple Online Demo

    【讨论】:

    • 最后一次支持的 Andy 升级 26-Feb-2009 ......见php.net/ChangeLog-5.php ...你比你想象的要多......
    • 感谢 eval.in 链接...非常值得收藏,不幸的是我使用的是 5.2.9
    猜你喜欢
    • 2019-09-06
    • 2014-06-28
    • 2016-07-30
    • 1970-01-01
    • 1970-01-01
    • 2020-04-03
    • 1970-01-01
    • 2016-12-19
    • 2017-01-27
    相关资源
    最近更新 更多