简体   繁体   中英

How to get the diff from two arrays in PHP

Hello i have this arrays

"restaurant_beers": [
      {
        "beer_id": "3"
      },
      {
        "beer_id": "2"
      },
      {
        "beer_id": "1"
      },
      {
        "beer_id": "18"
      },
      {
        "beer_id": "19"
      },
      {
        "beer_id": "23"
      },
      {
        "beer_id": "24"
      }
    ],
    "merged_beers": [
      {
        "beer_id": "2"
      },
      {
        "beer_id": "3"
      },
      {
        "beer_id": "1"
      },
      {
        "beer_id": "23"
      }
    ]

after making very much test with array_diff ,it returns the merged_beers array, any suggestion?

but im trying to get only the beer_id 18, 19, 24

is there any other way to do this? or maybe with a for?

thanks

array_diff expects a flat array, not a multidimensional array.

Use array_column() to extract the beer IDs from each array.

$diff = array_diff(array_column($array['restaurant_beers'], 'beer_id'),
                   array_column($array['merged_beers'], 'beer_id'));

This will return an array like

['18', '19', '24']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM