I have arra_filter functions that returns this:
Array(1) {
[3]=>
object(Timber\Term)#5173 (16) {
["PostClass"]=>
string(11) "Timber\Post"
["TermClass"]=>
string(4) "Term"
["object_type"]=>
string(4) "term"
["_children"]=>
NULL
["name"]=>
string(24) "Installation Maintenance"
["taxonomy"]=>
string(8) "category"
["id"]=>
int(73)
["ID"]=>
int(73)
["term_id"]=>
int(73)
["slug"]=>
string(24) "installation-maintenance"
["term_group"]=>
int(0)
["term_taxonomy_id"]=>
int(73)
["parent"]=>
int(39)
["count"]=>
int(1)
["filter"]=>
string(3) "raw"
["term_order"]=>
string(1) "0"
}
}
What I want is to remove key from array [3](sometimes is different number for key) and get the value. Tried flattening array but that didn't work, maybe because value is object?
Function that return that array is:
$filter = array_filter($arr,
function($item) use ($slug) {
return $item->slug == $slug;
}
);
Edit: Trying to clarify what I want to achieve. Srry if I wasn't from the start.
Is it possible to return only object so I can type something like
$filter->name
and not $filter[0]->name;
So this is the data I want:
Object {
object(Timber\Term)#5173 (16) {
["PostClass"]=>
string(11) "Timber\Post"
["TermClass"]=>
string(4) "Term"
...
}
CodePudding user response:
Instead of doing array_filter
(that always returns array of items), you should just use simple foreach
.
// @lang PHP8
private function findItem(array $items, string $slug): ?\Timber\Term
{
foreach ($items as $item) {
if ($item->slug === $slug) {
return $item;
}
return null;
}
}
$item = $this->findItem($items, $someSlug);
echo $item->slug ?? throw new \Exception("No item found with slug '{$slug}'");