doudandui1592 2016-04-11 01:20
浏览 33
已采纳

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!';
    }
}
  • 写回答

3条回答 默认 最新

  • 普通网友 2016-04-11 01:35
    关注

    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!';
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部