-4

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'
]
mickmackusa
  • 43,625
  • 12
  • 83
  • 136
Behzad
  • 75
  • 1
  • 7
  • Is this what you're after? https://www.php.net/manual/en/function.array-diff.php – Rob Eyre Mar 30 '23 at 20:39
  • Please can you do a var_dump() of both $array_one and $array_tow to confirm they have the same structure – Rob Eyre Mar 30 '23 at 20:41
  • 1
    Near duplicate (that does slightly more than required): [PHP - Finding the difference between Two Multidimensional Arrays with different structures based on one value](https://stackoverflow.com/q/44027153/2943403) – mickmackusa Mar 30 '23 at 21:14
  • Also related, with inverted filtering (intersections instead of differences): [Filter an array of objects by a flat array](https://stackoverflow.com/q/62261618/2943403) – mickmackusa Mar 30 '23 at 21:48

1 Answers1

0

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')
    )
);
mickmackusa
  • 43,625
  • 12
  • 83
  • 136