PHP – How to parse json data and compare it

  json, php

I hope you all having a great day. I’m developing a simple wordpress plugin and I’ve never worked with JSON encoded data on PHP before so I need some help here.

I have this simple function with a single parameter that’s called in a ‘foreach’ loop and inside this function I have an array of values pulled from DB and it’s JSON encoded, it goes like this:

array (size=4)
  0 => string '[{"videoUrl":"https://vimeo.com/493156200","playlistID":"7992"}]' (length=64)
  1 => string '[{"videoUrl":"https://vimeo.com/365531165","playlistID":"7992"}]' (length=64)
  2 => string '[{"videoUrl":"https://vimeo.com/365531139","playlistID":"7992"}]' (length=64)
  3 => string '[{"videoUrl":"https://vimeo.com/521605944","playlistID":"7992"}]' (length=64) 

My function goes like this:

$playlist_id = 7992;    
function videostatuschecker($x){
    $unlockedvideos = ['json encoded data illustrated above'];
    // x value is like this:  $x = 'https://vimeo.com/493156200';
           
    if (in_array($x, $unlockedvideos)){
       return 'unlocked';  
    }
    else{
      return 'locked';
   }
}

Video URL will be passed through my function’s parameter variable and playlist ID is defined in the parent function so it’s static.

Now what I need is, I need to compare that $x value to "videoUrl" values in the array and compare its ‘playlistID’ to $playlist_id variable and if they both match, I need the function to return ‘unlocked’ and vice versa for the else statement. Any help is much appreciated, thank you so much.

P.S: I’m a newbie in back-end development so I’d appreciate some answers with very simple examples. Thank you.

Source: Ask PHP

LEAVE A COMMENT