Laravel check an array of object which contain in another array

All we need is an easy explanation of the problem, so here it is.

I would like to get check my array of the object have title and id. I want to get all the array of objects where id exists in the existing array.

I tried using array_diff or array_intersect but error stating that it is supposed to be an array.

    if (!empty(session('selected_movies'))) {
        $current_movies = array_intersect($allMovies, session('selected_movies'));
    }

The array of objects data

    [
        {
            "id":"05595dd2-2f13-11ea-9e3f-42010a940008",
            "title":"Harry Potter"
        },
        {
            "id":"247d20cd-2f13-11ea-9e3f-42010a940008",
            "title":"Tom and Jerry"
        }
    ]

Existing array data

    ["247d20cd-2f13-11ea-9e3f-42010a940008", "51141418-4fb1-11ea-a428-7a79190f5c7d"]

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

You could do a simple foreach and just unset if its missing desired id

<?php
        //Enter your code here, enjoy!

$array = json_decode('[
        {
            "id":"05595dd2-2f13-11ea-9e3f-42010a940008",
            "title":"Harry Potter"
        },
        {
            "id":"247d20cd-2f13-11ea-9e3f-42010a940008",
            "title":"Tom and Jerry"
        }
    ]');
     $check = ["247d20cd-2f13-11ea-9e3f-42010a940008", "51141418-4fb1-11ea-a428-7a79190f5c7d"];
   foreach($array as $index => $current){
       if(!in_array($current->id,$check)) unset($array[$index]);
   }
   print_r($array);

alternativly if you want to create a new array

         $mah = [];
 foreach($array as $index => $current){
       if(in_array($current->id,$check)) array_push($mah,$current);
   }
   print_r($mah);

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply