Mohammad Umer
Mohammad Umer

Reputation: 534

How can we get key of next element key with foreach loop

I am getting xml array from an api and when please see it below I am using this foreach loop.

                    foreach ($event->raidstatus as $status){
                          //i want to get name and cound i tried $status->name but failed
                          //and when i did print_r($status) then got array
                          echo '<pre>'; print_r($status); exit;
                    }

This is print_r results

SimpleXMLElement Object
(
    [status0] => SimpleXMLElement Object
        (
            [id] => 0
            [name] => Bestätigt
            [count] => 1
        )

    [status1] => SimpleXMLElement Object
        (
            [id] => 1
            [name] => Angemeldet
            [count] => 3
        )

    [status2] => SimpleXMLElement Object
        (
            [id] => 2
            [name] => Abgemeldet
            [count] => 4
        )

    [status3] => SimpleXMLElement Object
        (
            [id] => 3
            [name] => Ersatzbank
            [count] => 0
        )

    [required] => 40
)

Please help me to get results Thanks

Upvotes: 0

Views: 65

Answers (1)

Nigel Ren
Nigel Ren

Reputation: 57121

If you just want to fetch the data from the <status...> elements, you are just 1 level short in your foreach() loop.

foreach ($event->raidstatus as $status){

is fetching the whole <raidstatus> element, you want all of the child nodes (using children() in this code) to get at the name elements...

foreach ($event->raidstatus->children() as $status){
    echo '<pre>'.$status->name.PHP_EOL;
}

Upvotes: 1

Related Questions