Jump to content

recursive function, help needed


AP81

Recommended Posts

Hi,

 

I have a number of arrays in which I need to reverse, however some arrays have multiple dimensions.  For example, given this array:

 

$input = array(1 => 'd', 4 => array(11 => 'x', 12 => 'y'), 5 => 'h', 9 => 'u');

 

I need to reverse all the elements, so the result would look like this:

$output = array(9 => 'u', 5 => 'h', 4 => array(12 => 'y', 11 => 'x'), 1 => 'd');

 

I'm part of the way, and have written this function:


$output = ReverseIt($input);

function ReverseIt($arr)
{

	foreach ($arr as $element){

		if (is_array($element)){
			$new_arr[] = (ReverseIt($element));
		} else {
			$new_arr[] = $element;
		}
	}
	return array_reverse($new_arr);
}

 

However, it doesn't maintain the indexes (obviously), and results in this output:

Array ( [0] => u [1] => h [2] => Array ( [0] => y [1] => x ) [3] => d )

]

 

Any ideas how I can do this?

Link to comment
https://forums.phpfreaks.com/topic/96636-recursive-function-help-needed/
Share on other sites

<?php
$input = array(1 => 'd', 4 => array(11 => 'x', 12 => 'y'), 5 => 'h', 9 => 'u');
echo '<pre>', print_r($input, true), '</pre>';

function reversIt ($a)
{
    $res = array_reverse($a, true);            // preserve keys
    foreach ($res as $k=>$b)
    {
        if (is_array($b))
        {
            $res[$k] = reversIt($b);
        }
    }
    return $res;
}

$new = reversIt($input);

echo '<pre>', print_r($new, true), '</pre>';
?>

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.