Jump to content

recursive function woes (reading multi-dim array)


nikefido

Recommended Posts

My function is supposed to read into a multi-dim array of unknown depth. However, my function is not recursing correctly :(

 

I am hoping that someone can spot the problem? I am getting no error returned.

 

LMK if it's too out-of-context!

 

<?php
echo "================";
function arrayToXml($myArray) {
if(!is_array($myArray)) {
	echo "not an array";
} else {

	static $reit = 0;
	if($reit == 0) {
		$output = "<structure>\n";
	}

	foreach($myArray as $xmlFile) {
		if(is_array($xmlFile)) {
			$output .= "<directory>\n";
			$reit ++;
			arrayToXml($xmlFile);
			//echo "<p>Directory: " . $xmlFile . "</p>";
			$output .= "</directory>\n";
		} else {
			$output .= "<file>: " . $xmlFile . "</file>\n";
			//echo "File: " . $xmlFile . "</p>";
		}//end if
	}//end foreach
	$output .= "</structure>";
	return htmlentities($output);
}//end is_array if
}//end funcion

echo "<pre>" . arrayToXml($files) . "</p>";
?>

What exactly is wrong with it?

sorry, probably should include that, huh?

 

It does not seem to be actually re-calling itself - my output has <directory></directory> but does not have anything in it:

 

<?xml version="1.0" encoding="UTF-8"?>
<structure>
<file>: /Users/Chris/Sites/_resources/.DS_Store</file>
<directory>
</directory>
<directory>
</directory>
<directory>
</directory>
<file>: /Users/Chris/Sites/_resources/AlphaMasking.zip</file>
<file>: /Users/Chris/Sites/_resources/ape_a045.zip</file>
<file>: /Users/Chris/Sites/_resources/BloodEffect.as</file>
<file>: /Users/Chris/Sites/_resources/dropMenu.ZIP</file>
<file>: /Users/Chris/Sites/_resources/Example.zip</file>
</structure>

If the main array's item is also an array, it is not reading into that array to find the data (file structure string) within :(

I think the main problem was you weren't apending the returned from the function to $output when it was being called from itself.

 

I rewrote to tidy it up a lil bit:

 

<?php
function arrayToXml($array,$start=TRUE){
if($start === TRUE){
	$output = "<structure>\n";
}
foreach($array as $v){
	if(is_array($v)){
		$output .= "<directory>\n".arrayToXml($v,FALSE)."</directory>\n";
	}else{
		$output .= '<file>: '.$v."</file>\n";
	}
}
if($start === TRUE){
	$output .= "</structure>\n";
	return htmlentities($output);//only apply htmlentities on last return
}
return $output;
}
echo arrayToXml($array);
?>

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.