PHP: array_filter for an object?

Viewed 16172

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. 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]);
3 Answers

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