PHP检查数组匹配条件中的值然后回显出该特定值

问题描述:

I'm trying to display movie information from the XML list that matches post title.

$movie_title is the variable of the movie name.

Now I have 2 problems:

  • If title doesn't match then else statement will echo out "No match!" for each move that doesn't match condition of the if statement.

  • How to limit result only on the first movie that match the title.

I'm also wondering if there is some better way to do this.

$movie_title = get_the_title();
$movies = simplexml_load_file('http://www.kolosej.si/spored/xml/2.0/');

foreach($movies as $movie) {

    $movie_list = $title=$movie->title;

    if((strpos($movie_list, $movie_title)) !== false) {

        echo $original_title=$movie->original_title . '<br>';
        echo $description=$movie->plot_outline;

    } else {
        echo 'No match!';
    }
}

This would work, by setting a $found when you actually find a matching movie title and only outputting a No Match if the $found is not set

<?php
$movie_title = get_the_title();
$movies = simplexml_load_file('http://www.kolosej.si/spored/xml/2.0/');
$found = false;

foreach($movies as $movie) {

    $movie_list = $title=$movie->title;

    if((strpos($movie_list, $movie_title)) !== false) {

        echo $original_title=$movie->original_title . '<br>';
        echo $description=$movie->plot_outline;
        $found = true;
        break;  // assuming there will only be one, else leave this out
    }

}
if ( ! $found ) {
    echo 'No match!';
}

replace your code with the following code

<?php 
$movie_title = get_the_title();
$movies = simplexml_load_file('http://www.kolosej.si/spored/xml/2.0/');
$array_m =  (array) $movies ;

if(in_array($movie_title,array_column($array_m,'title'))) 
{
    echo $original_title=$movie->original_title . '<br>';
    echo $description=$movie->plot_outline;

} 
else 
{
    echo 'No match!';
}
?>  

You could use in_array() as suggested in the comments, or alter your code slightly, so that you cancel the loop, when you found a match, or when the loop finished without finding one, you display "No match"

Be careful: in_array() does not check for substings, like you want, but only for whole movie titles.

 $movie_title = get_the_title();
 $movies = simplexml_load_file('http://www.kolosej.si/spored/xml/2.0/');

foreach($movies as $movie) {

  $movie_list = $title=$movie->title;

  if((strpos($movie_list, $movie_title)) !== false) {
    echo $original_title=$movie->original_title . '<br>';
    echo $description=$movie->plot_outline;
    $found = true;
    break;
  }
}
if(!$found)
  echo "Not found!";