Jump to content

Convert this into Recursive Function?


NeoMarine

Recommended Posts

Hey,

 

I have a multidimensional array which is created already and I need to Sort it by the values inside. Although I have figured out how to do this normally, I cannot figure out how to do it through a recursive function so I dont need to keep creating the same code over and over inside of it just to create an additional loop.

 

Here is my code:

 

				$newFileArray=array();

				$levelSize0=sizeof($levelFileArray[0]);
				$levelSize1=sizeof($levelFileArray[1]);
				$levelSize2=sizeof($levelFileArray[2]);

				for ($iL0=0; $iL0!=$levelSize0; $iL0++){
					$newFileArray[] = $levelFileArray[0][$iL0];

					for ($iL1=0; $iL1!=$levelSize1; $iL1++){

						if ($levelFileArray[0][$iL0]['ID']==$levelFileArray[1][$iL1]['RepliedToStartID']){

							//Matching start id
							$newFileArray[] = $levelFileArray[1][$iL1];

							# REPEAT POINT ("START POINT")
							for ($iL2=0; $iL2!=$levelSize2; $iL2++){

								if ($levelFileArray[1][$iL1]['ID']==$levelFileArray[2][$iL2]['RepliedToStartID']){

									//Matching start id
									$newFileArray[] = $levelFileArray[2][$iL2];

									# REPEAT POINT 2 ("START POINT")
									// Normally I would keep adding code here to add another loop

									unset($levelFileArray[2][$iL2]);

								}

							}

							unset($levelFileArray[1][$iL1]);

						}

					}
				}

 

$levelFileArray is my multidimensional array I wish to sort through the recursive function.

 

However, since I need to add a new value to the $newFileArray, every time I return the array, it returns it as a "whole" instead of a single value so I cannot figure out how to go about what I'm doing about in a more "infinite" way?

Link to comment
https://forums.phpfreaks.com/topic/148923-convert-this-into-recursive-function/
Share on other sites

try

<?php

function xyz($a, $b){
$newFileArray = array();
for ($i = 0; $i < count($a); $i++){
	$newFileArray[] = $a[$i];
	for ($j = 0; $j < count($b); $j++){
		if ($a[$i]['ID']==$b[$j]['RepliedToStartID']) $newFileArray[] = $b[$j];
	}
}
return $newFileArray;
}

$newFileArray = array_shift($levelFileArray);
while (!empty($levelFileArray)){
$next = array_shift($levelFileArray);
$newFileArray = xyz($newFileArray, $next);
}

?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.