带条件的嵌套foreach语句

时间:2018-07-31 21:53:19

标签: php foreach conditional nested-loops

我有以下XML数据:

<MEET>
    <CLASS>
        <NAME>Professional</NAME>
    </CLASS>
    <CLASS>
        <NAME>Amateur</NAME>
    </CLASS>
    <EVENT>
        <NAME>Event One</NAME>
    </EVENT>
    <EVENT>
        <NAME>Event Two</NAME>
    </EVENT>
    <EVENT>
        <NAME>Event Three</NAME>
    </EVENT>
    <ATHLETE>
        <NAME>Joe Smith</NAME>
        <ADDRESS>123 Main St, Anytown, NY 12121</ADDRESS>
        <EMAIL>joe@smith.com</EMAIL>
        <PHONE>518-555-1234</PHONE>
        <EMERGENCYNAME>Jane Smith</EMERGENCYNAME>
        <EMERGENCYPHONE>518-555-5678</EMERGENCYPHONE>
        <CLASS>Amateur</CLASS>
    </ATHLETE>
</MEET>

以及以下PHP:

<?php
$xml = simplexml_load_file('url');
foreach ($xml->CLASS as $classes) {
    echo '<h1>'.$classes->NAME.'</h1>';
    foreach ($xml->EVENT as $events) {
        echo '<h2>'.$classes->NAME.': '.$events->NAME.'</h2>';
        foreach($xml->ATHLETE as $athletes) {
            if (strpos($athletes->CLASS, $classes->NAME) !== false) {
                echo $athletes->NAME;
            }
        }
    }
}
?>

我无法获得Joe Smith的名字在H1 Amateur标题下,H2 Amateur: Event One Amateur: Event TwoAmateur: Event Three子标题下输出。

如果我将Strpos中的$needle替换为Amateur,它将在两个类的每个事件中输出Joe Smith。

1 个答案:

答案 0 :(得分:4)

如果您使用var_dump函数查看变量的实例是什么,它可能会告诉您$athletes->CLASS$classes->NAME的类型为SimpleXMLElement

如果要将它们进行比较,则必须将if语句更改为以下形式:

if (strpos($athletes->CLASS->__toString(), $classes->NAME->__toString()) !== false) {
    echo $athletes->NAME;
}