繁体   English   中英

PHP的:对象的array_filter?

[英]PHP: array_filter for an object?

我有一个需要过滤某些内容的数组,例如,我可能只希望将星期几作为星期五的记录。 据我所知,这从未奏效,但它正在使用一个对象并在其上使用array_filter 能行吗? 有没有更好的方法或方法可以对对象执行此操作?

public function filterByDow($object)
{
    $current_dow=5;
    return array_values(array_filter($object, function ($array) use ($current_dow) {
        $array = (array) $array;
            if(!empty($array['day_id']) && $array['day_id'] > -1){
                if($array['day_id'] != $current_dow){
                    return false;
                }
            }
            return true;
    }));
}

$object = $this->filterByDow($object);

样本数据可能像这样:

$object = (object) array(['id' => '1', 'day_id' => 3], ['id' => '2', 'day_id' => 4]);

尝试这个

    <?php
$items = array(['id' => '1', 'day_id' => 3], ['id' => '2', 'day_id' => 5]);
function filterByDow($items, $dow = 5){
    return array_filter($items, function($item) use ($dow) {
        if($item['day_id'] == $dow){
            return true;
        }
    });

}

$resultArr = filterByDow($items);
print_r($resultArr);
?>

尝试创建一个集合并实现用于过滤的方法。

class Offer
{
    private $dayId;

    public function getDayId()
    {
        return $this->dayId;
    }

    public function setDayId($dayId)
    {
        return $this->dayId = $dayId;
    }
}

class OfferCollection
{
    const FRIDAY = 5;

    static $dayIds = [
        self::FRIDAY => 'Friday'
    ];

    private $offers = [];

    public function addOffer(Offer $offer)
    {
        $this->offers[] = $offer;
    }

    public function getOffersByDay($dayId)
    {
        $offers = [];

        if (in_array($dayId, self::$dayIds)) {
            foreach ($this->offers as $offer) {
                if ($offer->getDayId == $dayId) $offers[] = $offer;
            }
        }

        return $offers;
    }
}

从评论来看,数组是一个laravel集合,我猜答案是:

$filtered = $collection->filter(function ($value, $key) { 
    return $value['day_id'] == 5; 
});

https://laravel.com/docs/5.7/collections#method-filter

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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