Wednesday, July 1, 2009

Re: Problem returning array from function

Ok Sanfly, let's walk through the cases of calling the makeBreadcrumb
function:
1) with $id = 1 and it has no parent;
2) with $id = 2 and it has one parent (9);

Case 1:
1) Parameters: $array(0) = 1, $id = 1;
2) Statements:
$parent = $this->GallerysCat->find("GallerysCat.id = '$id'",
"parent");
$parent = $parent['GallerysCat']['parent'];
results in $parent = 0;
3) Enters:
if ( $parent == 0 ) {
4) Reverses array
$reverse = array_reverse($array);
results in $reverse(0) = 1;
5) Returns reversed array
return $reverse;
results in return of $reverse(0) = 1;
6) END OF CASE 1 - no problems!

Case 2:
1) Parameters: $array(0) = 2, $id = 2;
2) Statements:
$parent = $this->GallerysCat->find("GallerysCat.id = '$id'",
"parent");
$parent = $parent['GallerysCat']['parent'];
results in $parent = 9;
3) Skips:
if ( $parent == 0 ) {
4) Enters:
else{
5) Adds parent to $array:
$array[] = $parent;
results in $parent(0) = 2, $parent(1) = 9;
6) Calls recursively:
$this->makeBreadcrumb($array, $parent);
6.1) Parameters: $parent(0) = 2, $parent(1) = 9, $id = 9;
6.2) Statements:
$parent = $this->GallerysCat->find("GallerysCat.id = '$id'",
"parent");
$parent = $parent['GallerysCat']['parent'];
results in $parent = 0;
6.3) Enters:
if ( $parent == 0 ) {
6.4) Reverses array
$reverse = array_reverse($array);
results in $reverse(0) = 9, $reverse(1) = 2;
6.5) Returns reversed array
return $reverse;
results in return of $reverse(0) = 9, $reverse(1) = 2;
6.6 END OF RECURSIVE CALL!!!
7) END OF CASE 2

Now do you see that after making the recursive call to the function,
the returned result is not being used and thus you are not returning
it!

Suggested change in the else block:
return ( $this->makeBreadcrumb($array, $parent) );

When you are using recursive calls, each call has it own scope of
variables, so $array is not the same in both!!!

Enjoy,
John

On Jul 1, 9:06 am, Sanfly <san...@gmail.com> wrote:
> Oh, and Ive set my debug to 2 and dont get any errors
>
> The problem is not building the array, the problem is returning the
> built array
>
--~--~---------~--~----~------------~-------~--~----~
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: