E4bd1595f34e7e03765eda6ed65bf6bb

I tried using array_walk to search through a multidimensional array (5 levels deep) and find any arrays that contain a single item, and if so, convert the array to a string, but it didn't work, can someone re-factor the code, possibly give me a solution that can be as many levels deep and still turn single itemed arrays into a string?

<?php
foreach($final as $key => $val) {
    if (is_array($val) && count($val) == 1) $final[$key] = $val[0];
    if (is_array($val))			
    foreach ($val as $skey=>$sval) {
        if (is_array($sval) && count($sval) == 1) $final[$key][$skey] = $sval[0];
        if (is_array($sval))
        foreach($sval as $sskey=>$ssval) {
            if (is_array($ssval) && count($ssval) == 1) $final[$key][$skey][$sskey] = $ssval[0];
            if (is_array($ssval))
            foreach($ssval as $ssskey=>$sssval) {
                if (is_array($sssval) && count($sssval) == 1) $final[$key][$skey][$sskey][$ssskey] = $sssval[0];
            }
        }
    }
}
?>

Refactorings

No refactoring yet !

5ac8526027625a913a2262d7f5b1efc8

bob-the-destroyer.myopenid.com

September 16, 2010, September 16, 2010 05:29, permalink

No rating. Login to rate!

I think this "recursive_extract()" function should do it. As many dimensions as your PHP setup can handle. This function returns a numeric key array of all isolated arrays found. I'm not sure what you meant by returning it as a string though. Do "implode()" on the returned array...?

<?php

function recursive_extract(array $array) {
	static $return_array = array();
	
	foreach ($array as $sub_array) {
		if (is_array($sub_array)) {
			if (count($sub_array) === 1) {
				$return_array[] = current($sub_array);
				return;
				}
			$return = recursive_extract($sub_array);
			if (count($return) === 1) {
				$return_array[] = current($return);
				return;
				}
			}
		}
	return $return_array;
	}

// testing this new recursive_extract() function...
$test_array = array(
	array(
		array(1,2,3),
		array(
			array(2,3),
			array(346,23),
			array(
				'test' => 2
				)
			),
		array(62436)
		),
	array(
		array(6345,3462),
		array("x")
		)
	);
	
var_dump(recursive_extract($test_array));

/* dumps this text...
array(3) {
  [0]=>
  int(2)
  [1]=>
  int(62436)
  [2]=>
  string(1) "x"
}

*/

?>
5ac8526027625a913a2262d7f5b1efc8

bob-the-destroyer.myopenid.com

September 16, 2010, September 16, 2010 06:14, permalink

No rating. Login to rate!

Woops! Line 19 in my refactoring above should be "$final_array = $return_array; $return_array = array(); return $final_array;". Basically, you need to wipe the functions "memory". Otherwise, whenever you call recursive_extract() again, it will still carry values from the first array you gave it.

Needs to be an edit feature.

Your refactoring





Format Copy from initial code

or Cancel