Search code examples
phpforeachconditional-statementsnested-loops

Nested foreach statements with conditional


I have the following XML Data:

<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>[email protected]</EMAIL>
        <PHONE>518-555-1234</PHONE>
        <EMERGENCYNAME>Jane Smith</EMERGENCYNAME>
        <EMERGENCYPHONE>518-555-5678</EMERGENCYPHONE>
        <CLASS>Amateur</CLASS>
    </ATHLETE>
</MEET>

And the following 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;
            }
        }
    }
}
?>

And I cannot get Joe Smith's name to output beneath the H1 Amateur heading, under the H2 Amateur: Event One Amateur: Event Two and Amateur: Event Three subheadings.

If I replace the $needle in my strpos with Amateur, it outputs Joe Smith in every event in BOTH classes.


Solution

  • If you use var_dump function to see what is the instance of your variable, it could show you that the type of $athletes->CLASS and $classes->NAME are SimpleXMLElement.

    If you want to compare them together you must change your if statement to something like this:

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