tags:

views:

109

answers:

2

If the format is the following, where c is an object array that I must foreach through each iteration:

$a->b->c

And I do:

$z = $a->b
foreach($z as $key => $value)
echo $value['field'];

$key comes up as null, even though I have valid values. How do I get the name of the object?

+2  A: 

Considering the following piece of XML and the code to load it with SimpleXML :

$str = <<<XML
<root>
    <a>
        <b>
            <c>glop</c>
            <d>test</d>
        </b>
    </a>
</root>
XML;
$xml = simplexml_load_string($str);

You could "cast" $xml->a->b to an array, to be able to iterate over it :

foreach ((array)$xml->a->b as $name => $value) {
    echo "$name : $value<br />";
}

And you'll get this kind of output :

c : glop
d : test

(maybe not exactly the same XML string as yours, but I hope this will help you get to the solution -- if it does, can you edit your question to show us you XML data, and the output you'll willing to get ? )

Quoting the manual page, at the Converting to array section :

If an object is converted to an array, the result is an array whose elements are the object's properties.
The keys are the member variable names, with a few notable exceptions: integer properties are unaccessible; private variables have the class name prepended to the variable name; protected variables have a '*' prepended to the variable name.

Pascal MARTIN
This is an object that is using ArrayAccess. I'm not sure that your solution would work for it.
Citizen
Hu ; you mean it has nothing to do with SimpleXML ? (there is "simplexml" in the title of your question, so I might kinda have taken quite a shortcut ^^ )
Pascal MARTIN
It is using simpleXML, the object is an object that implements the ArrayAccess interface, and your answer was actually correct :)Adding (array) to the front of my foreach caused my $key to get the correct value, instead of returning a NULL value.
Citizen
OK -- thanks for the clarification :-) I have to admit I had a moment of doubt ^^ ;; have fun !
Pascal MARTIN
+5  A: 

XML:

<a>
  <b>
    <c />
    <d />
    <e />
  </b>
</a>

PHP Code:

$xml = new SimpleXMLElement($file_url, true);
foreach($xml->b->children() as $node) {
    echo $node->getName() . "\n";
}

Would give you:

c
d
b

See PHP's manual for further reference.

Koraktor
This also works, but his answer was first :)
Citizen
This is a more elegant and OO based solution utilizing SimpleXML better.
jW