Home » Php » json – Display and check for multiple key in php echo

json – Display and check for multiple key in php echo

Posted by: admin February 25, 2020 Leave a comment

Questions:

I am trying to output a key value from JSON data and want to check for multiple keys.

I want to display the title of a movie and or tv show.

                        if($channel=="multi" AND !empty($movies)){
                        foreach ($movies as $movie) {
                            if(!empty($movie['poster_path'])){
                                echo '<div class="mov">
                            <a href="'.$movie['media_type'].'/'.$movie['id'].'">
                                <img src="https://image.tmdb.org/t/p/w185'.$movie['poster_path'].'">
                                <h2 class="title">'.$movie['title'].'</h2>
                            </a>
                        </div>';
                            }
                        }
                    }

whereas <h2 class="title">'.$movie['title'].'</h2> also needs to check for <h2 class="title">'.$movie['name'].'</h2>

How can I check for both ‘title’ and ‘name’ in the same go?

I am pretty new to all this and learning on the go. So please correct me as well if there are any mistakes in my coding!

How to&Answers:

If you’re trying to get $movie[‘title’] or $movie[‘name’] (because you’re unsure what the variable will be called) you can use an if statement. (This is not a pretty way of writing it — but it is the clearest way).

 if($channel=="multi" AND !empty($movies)){
   foreach ($movies as $movie) {
     if(!empty($movie['poster_path'])){
       echo '<div class="mov">
             <a href="'.$movie['media_type'].'/'.$movie['id'].'">
               <img src="https://image.tmdb.org/t/p/w185'.$movie['poster_path'].'">
               <h2 class="title">';

               //AN IF STATEMENT TO CHOOSE EITHER TITLE OR MOVIE
               if(!empty($movie['title']) {
                 echo $movie['title'];
               } else {
                 echo $movie['name'];
               }

              echo .'</h2>
              </a>
              </div>';
     }
   }
 }

Alternatively, you could also make $movie[‘title’] equal to $movie[‘name’] if it is not blank.

 if($channel=="multi" AND !empty($movies)){
   foreach ($movies as $movie) {
     if(!empty($movie['poster_path'])){
    // MAKE MOVIE TITLE = MOVIE NAME IF IT IS NOT BLANK
     if(!empty($movie['name'])){
       $movie['title'] = $movie['name'];
     }
       echo '<div class="mov">
             <a href="'.$movie['media_type'].'/'.$movie['id'].'">
               <img src="https://image.tmdb.org/t/p/w185'.$movie['poster_path'].'">
               <h2 class="title">'.
                 $movie['title'].
              '</h2>
              </a>
              </div>';
     }
   }
 }

There are usually many ways to solve a problem. Think through the logic. If this than that. If not this, than that instead.