无法比较PHP中IF语句中的两个字符串

时间:2015-03-05 10:47:00

标签: php xml logic

好的,所以我一直在尝试为一个需要从2个XML文件中获取信息的Web应用程序构建服务器端,并一次比较一个元素。出于某种原因,除了比较2个节点之外,我的代码将执行所有操作。

代码:

function getCoursesByRole($role){
    s("role is ". $role);
    $xml = getxml(); # get the XML file
    $roles = getRoles();#load the roles file
    $modules = array();
    foreach($roles->children() as $project){
    s($project->name);
        if($project->name == $role){
            s("found:". $role);
            $courses = $project->courses->children();
            #echo "courses   ". $courses;
            foreach($courses as $theCourse){
                foreach($xml->children() as $course){
                    s("looking for $theCourse.... found ".$course->name);
                    if($theCourse == $course->name){
                        s("found $theCourse");
                        array_push($modules, array('name' => $course->name));
                        break;
                    }
                }
            }
        }
    }
    #echo array_values($modules);
    return $modules;
}

从输出中我认为问题是一个逻辑问题。

role is core
core
found:core
looking for Fire Safety.... found Administration of Medication
looking for Fire Safety.... found An Introduction to GIRFEC
looking for Fire Safety.... found Equality and Diversity
looking for Fire Safety.... found Fire Safety
looking for Fire Safety.... found Food Safety
looking for Fire Safety.... found Infection Control
looking for Fire Safety.... found Introduction to Health and Safety
looking for Fire Safety.... found Introduction to Safer Handling
looking for Fire Safety.... found Managing Volunteers
looking for Fire Safety.... found QStar

我只展示了s("looking for $theCourse.... found ".$course->name);的一次迭代,它已经很长了

如果有人能看到解决方案,我会非常感激:)

1 个答案:

答案 0 :(得分:0)

  

在使用条件if(trim($ a)== trim($ b))时,使用trim()函数修剪字符串总是好主意。 - 离岸

这条评论回答了我的问题。更改此行后:if($theCourse == $course->name){到此if(trim($theCourse) == trim($course->name)){代码完美无缺。