Jump to content

Looping thru a multi-dimensional array


watagal
 Share

Recommended Posts

Greetings-All weekend, I've been trying to walk through an array where the elements can be specific data or another sub array. The nested arrays (or depth) is unknown. I've determined "array_walk()" and "array_walk_recursive()" won't work for me because it doesn't provide feedback on the depth (which I need). So I have been trying with "foreach()" statements. The problem is I don't think hardcoding a specific number of nested foreach() statements is a good solution.There must be a better approach. Any help is appreciated (as always).Gal

Link to comment
Share on other sites

What are you trying to accomplish?You are trying to get the depth of a multi-dimensional array?Well... A nested foreach loop seems like the only way to do it. I looked through the PHP array reference and couldn't find a function to determine the depth of an array.

function array_depth($array){       $array_depth = 1;       foreach ($array as $v)       {             if (is_array($v))             {                  $i = 1;                  $i += array_depth($v);                  if ($i > $array_depth)                  $array_depth = $i;             }       }       return $array_depth;}

That should work

Link to comment
Share on other sites

ThanksI'm querying my database with the results building a single multi-dimensional array where the nested depth is determined by the DB query. In other words, it will vary at runtime. This data will eventually populate a javascript tree (menu) control. The array is built in PHP and transferred to JS array.I'm trying to read the PHP array in order to replicate it in JS.This may not be the best way, if not - someone please let me know.TiA, Gal

Link to comment
Share on other sites

Ok, let's see if I'm on the right track?My assumptions:1) We can recursively call the same function.2) Variable scope is limited to within each recursive call of the same function. In other words, each time I call the function "addNode()", a whole new set of variables are created in memory.3) Except when I use pointer references (as in &$d and &$photoTag) and any modification made is visible in any of the recursive calls4) Am I using pointer references correctly?The top array is a sample PHP array and this code should transfer it to the bottom javascript sample.Are my assumption correct?TiA, Gal

/* 			//PHP Node Array where ## = IDs to $photoTag[]:$node[	'1'=>													0=$depth		[11,'12'=>										 1			[23,24,25, '26'=>						   2				[31,32,33,34,35]						3/2			,27,28]										  1		,13]												  0	,'2'=>		[17,'18'=>										 1			[23,24,25,'26'=>							2					[31,32,'33'=>							 3					[41,42,'43'=>						 4						[51,52,53,54,55]				 5/4					]											3				,34,35]									   2			,27,28]										   1		,19]												   0];*/$d=0;	echo "var aTreeNodes = [";addNode($node);echo "];";function addNode($arr) {	$arrMax = count($arr);	foreach($arr as $key => $id) {		if (count($id) > 1) {							echo "[".&$photoTag[$key]['name'].",".$key.",";	// Add "folder" node			&$d++;	addNode($id);	&$d--;	// Dive into SubArray		} else {											echo "[".&$photoTag[$id]['name'] .",".$id."]";	// Add "item" node		}		if ($id != $arr($arrMax))	echo ",";			// NOT Last element	}	if (&$d > 0)	echo "],";	else			   echo "]";}/* Javascriptvar aTreeNodes = [	['NodeText', 1, 		['NodeText',11],		['NodeText',12,			['NodeText',23],			['NodeText',24],			['NodeText',25],			['NodeText',26, 				['NodeText',31],				['NodeText',32], 				['NodeText',33],				['NodeText',34],				['NodeText',35]			],			['NodeText',27],			['NodeText',28]		],		['NodeText',13]	],	['NodeText', 2, 		['NodeText',17],		['NodeText',18,			['NodeText',23],			['NodeText',24],			['NodeText',25],			['NodeText',26, 				['NodeText',31],				['NodeText',32], 				['NodeText',33,					['NodeText',41],					['NodeText',42], 					['NodeText',43,						['NodeText',51],						['NodeText',52], 						['NodeText',53],						['NodeText',54], 						['NodeText',55]					],				],				['NodeText',34],				['NodeText',35]			],			['NodeText',27],			['NodeText',28]		],		['NodeText',19]	]];					 */

Link to comment
Share on other sites

OK, it's kinda hard to extract the logic from your code but one thing I can tell you is that you are using pointers/references incorrectly. Yes, every time you call a function, the variables you declare in that function are created in memory. PHP's automatic garbage collection will destroy the variables and free the memory associated with those variables once the function has finished its execution. If you want to keep those variables when you execute the function again, you must create those variables outside the scope of the function (global variables) or you must declare those variables inside the function as static variables. Static variables won't be picked up by PHP's garbage collection once the function has finished its execution.http://www.php.net/variables.scope

function addNode($arr){	 static $d = 0; // for example	 // rest of your function}

OR

$d = 0;function addNode($arr){	 $d &= $GLOBALS['d']; // This should accomplish the same thing as static variables. /*I would recommend you use static variables, however, just in case later you want to use $d for a different purpose in the global scope.Static variables can only be accessed within its own function*/}

I think/hope that answers a couple of your questions.

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...