doudandui1592 2016-04-11 09: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 09: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条)

报告相同问题?

悬赏问题

  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示