Within my WordPress environemnt, I have a PHP challenege I can’t wrap my brain around. I have an array called $tax_terms
. I want to remove the item that has a sub property of name equal to ‘Staff’.
For a visual understanding, here is my array
$tax_terms
with echo '<pre>' . var_export($tax_terms, true) . '</pre>';
, it prints the following to page…
array (
2 =>
WP_Term::__set_state(array(
'term_id' => 400,
'name' => 'Staff',
'slug' => 'staff',
'term_group' => 0,
'term_taxonomy_id' => 400,
'taxonomy' => 'business',
'description' => '',
'parent' => 0,
'count' => 0,
'filter' => 'raw',
'term_order' => '0',
)),
3 =>
WP_Term::__set_state(array(
'term_id' => 362,
'name' => 'Customers',
'slug' => 'Customers',
'term_group' => 0,
'term_taxonomy_id' => 362,
'taxonomy' => 'business',
'description' => '',
'parent' => 0,
'count' => 1,
'filter' => 'raw',
'term_order' => '0',
)),
//...more array items...
)
The following works when I use array_filter() on it like so…
$tax_terms = array_filter($tax_terms, function ($value) use ($tax_terms) {
return $value != $tax_terms['2'];
});
But I don’t want to do it that way. I want to know what I am removing based on the ‘name’ => ‘Staff’ value like so…
$tax_terms = array_filter($tax_terms, function ($value) use ($tax_terms) {
return $value != $tax_terms->name['Staff'];
});
but that does not work and I don’t know why yet…Thanks for helping me learn how do this right.
>Solution :
Your $value
function argument is an entire $tax_term
item. You need to compare the property against the string Staff
.
$tax_terms = array_filter($tax_terms, function($tax_term) use($tax_terms){
return $tax_term->name != 'Staff';
});
Another way would be to iterate through the tax_terms
array using foreach
:
$filtered_tax_terms = [];
foreach($tax_terms as $tax_term){
if( $tax_term->name != 'Staff' ){
$filtered_tax_terms[] = $tax_term;
}
}