AP81 Posted March 18, 2008 Share Posted March 18, 2008 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? Quote Link to comment Share on other sites More sharing options...
Barand Posted March 18, 2008 Share Posted March 18, 2008 <?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>'; ?> Quote Link to comment Share on other sites More sharing options...
AP81 Posted March 18, 2008 Author Share Posted March 18, 2008 Spot on. Thanks! Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.