英文:
Remove elements from a flat array if found in a column of an array of objects
问题
我需要过滤一个一维值数组,根据对象数组中的特定属性/列。以下是您提供的代码示例:
$array_one = array_keys(wc_get_account_menu_items());
$array_two = $wpdb->get_results("SELECT pa_menu_endpoint FROM $phantom_menu WHERE pa_menu_from='pa_custom_tab'");
这两个数组的示例数据如下:
$array_one = [
'dashboard',
'orders',
'downloads',
'edit-address',
'woo-wallet',
'edit-account',
'customer-logout',
'test',
'testtest'
];
$array_two = [
(object) ['pa_menu_endpoint' => 'test'],
(object) ['pa_menu_endpoint' => 'testtest']
];
您想要从$array_one
数组中排除"pa_menu_endpoint"值,期望的过滤结果如下:
[
'dashboard',
'orders',
'downloads',
'edit-address',
'woo-wallet',
'edit-account',
'customer-logout'
]
请注意,这是如何使用PHP过滤$array_one
数组以排除与$array_two
中的"pa_menu_endpoint"值匹配的元素。
英文:
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'
]
答案1
得分: 0
你可以使用array_udiff()
和空合并运算符直接通过比较回调来过滤二维数组$array_one
,当$a
或$b
不是对象时,可以回退到$array_tow
的值。
var_export(
array_udiff(
$array_tow,
$array_one,
fn($a, $b) => ($a->pa_menu_endpoint ?? $a) <=> ($b->pa_menu_endpoint ?? $b)
)
);
也许更容易理解的方法是预先展平过滤数组$array_one
,这需要两个函数调用,但无需自定义回调。
var_export(
array_diff(
$array_tow,
array_column($array_one, 'pa_menu_endpoint')
)
);
英文:
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')
)
);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论