I have a one-dimensional array of values in one array and I need to filter it by a particular property/column in an array of objects.
My input arrays are populated by the following code:
$array_one = array_keys(wc_get_account_menu_items());
$array_tow = $wpdb->get_results("SELECT pa_menu_endpoint FROM $phantom_menu WHERE pa_menu_from='pa_custom_tab'");
Example data for these arrays:
$array_one = [
'dashboard',
'orders',
'downloads',
'edit-address',
'woo-wallet',
'edit-account',
'customer-logout',
'test',
'testtest'
];
$array_tow = [
(object) ['pa_menu_endpoint' => 'test'],
(object) ['pa_menu_endpoint' => 'testtest']
];
How can I exclude "pa_menu_endpoint" values from the $array_one
array.
Desired filtered result:
[
'dashboard',
'orders',
'downloads',
'edit-address',
'woo-wallet',
'edit-account',
'customer-logout'
]
You can filter the flat $array_tow
array by the two dimensional array_one
array directly using array_udiff()
and the null coalescing operator in the comparing callback to fallback to the $array_tow
value when $a
or $b
is not an object.
Code: (Demo)
var_export(
array_udiff(
$array_tow,
$array_one,
fn($a, $b) => ($a->pa_menu_endpoint ?? $a) <=> ($b->pa_menu_endpoint ?? $b)
)
);
Perhaps simpler to understand will be to pre-flatten the filtering array ($array_one
) -- this is two function calls, but no custom callbacks.
Code: (Demo)
var_export(
array_diff(
$array_tow,
array_column($array_one, 'pa_menu_endpoint')
)
);