简体   繁体   English

PHP的:对象的array_filter?

[英]PHP: array_filter for an object?

I have an array that I need to filter for certain things, for example, I might only want records that have the day of the week as Friday. 我有一个需要过滤某些内容的数组,例如,我可能只希望将星期几作为星期五的记录。 As far as I'm aware this has never worked but it's taking an object and using array_filter on it. 据我所知,这从未奏效,但它正在使用一个对象并在其上使用array_filter Can this work? 能行吗? Is there a better way or a way to do this on with object? 有没有更好的方法或方法可以对对象执行此操作?

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

Sample data might be like: 样本数据可能像这样:

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

try this 尝试这个

    <?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);
?>

Try to create a collection and implement methods for filtering in it. 尝试创建一个集合并实现用于过滤的方法。

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;
    }
}

As from the comments the array is a laravel collection I guess the answer is: 从评论来看,数组是一个laravel集合,我猜答案是:

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

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

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

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