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