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
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>';
?>

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.