Wednesday, April 29, 2009

Using RecursiveIteratorIterator on array from $this->find('threaded')

Hi All

I'm having a go at trying to use some of the classes from the PHP5 SPL
to produce a nested list based on the results of a find('threaded')
but I'm just stuck, so I was wondering if anybody was familiar with
these classes and could throw a few tips my way. (BTW this is as much
an exercise in learning to use the SPL as anything else).

The array produced by my $this->find('threaded') looks like this:

<code>
Array
(
[0] => Array
(
[Node] => Array
(
[title] => Welcome
[slug] => home
)

[children] => Array
(
)

)

[1] => Array
(
[Node] => Array
(
[title] => About Us
[slug] => about-us
)

[children] => Array
(
[0] => Array
(
[Node] => Array
(
[title] => Our Studio
[slug] => studio
)

[children] => Array
(
)

)

[1] => Array
(
[Node] => Array
(
[title] => Professional Video
[slug] => professional-video
)

[children] => Array
(
[0] => Array
(
[Node] => Array
(
[title] => Schools
Test
[slug] => schools-
test
)

[children] => Array
(
)

)

)

)

[2] => Array
(
[Node] => Array
(
[title] => Interest Free Credit
[slug] => buy-now-pay-later
)

[children] => Array
(
)

)

)

)

[2] => Array
(
[Node] => Array
(
[title] => Template
[slug] => template
)

[children] => Array
(
)

)
etc.
</code>

My code in the view is as follow (I used the code in the section on
SPL in the Zend PHP5 Certification Study Guide as a basis)

<code>
class Test_Iterator extends RecursiveIteratorIterator {

public function beginChildren(){

if (($this->getDepth() % 3) && $this->getDepth() > 2 ) {
echo str_repeat("\t", $this->getDepth() - 1);
echo "<ul>" . PHP_EOL;
}
}

public function endChildren(){
if (($this->getDepth() % 3) && $this->getDepth() > 2 ) {
echo str_repeat("\t", $this->getDepth() - 1);
echo "</ul>" . PHP_EOL;
}
}
}

class RecursiveArrayObject extends ArrayObject {
public function getIterator() {
return new RecursiveArrayIterator($this);
}
}

$it = new Test_Iterator(new RecursiveArrayObject($data));

echo("<ul>" . PHP_EOL);
$str = '';

foreach ($it as $key => $value) {
if($key == 'title'){
echo "<li>$value</li>" . PHP_EOL;
}
}

echo('</ul>');
</code>

The trouble is that anywhere I have an empty [children] array() it is
echoing out a pair of empty <ul> tags and I just can't figure out how
to filter them out...

Any insight would be greatly appreciated !

Cheers John

--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups "CakePHP" group.
To post to this group, send email to cake-php@googlegroups.com
To unsubscribe from this group, send email to cake-php+unsubscribe@googlegroups.com
For more options, visit this group at http://groups.google.com/group/cake-php?hl=en
-~----------~----~----~----~------~----~------~--~---

No comments: