0

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"]
5
  • why not just do a loop? Commented May 30, 2021 at 3:48
  • you meant do a foreach loop and check whether this id exist in that array? Commented May 30, 2021 at 3:49
  • yapp precisly that Commented May 30, 2021 at 3:51
  • ok but it brings to another problem how do I push an object to a new array? because when i push it become an array of array Commented May 30, 2021 at 4:03
  • updated my answer with alternative to push or to remove Commented May 30, 2021 at 4:10

1 Answer 1

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);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.