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? Link to comment https://forums.phpfreaks.com/topic/96636-recursive-function-help-needed/ 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>'; ?> Link to comment https://forums.phpfreaks.com/topic/96636-recursive-function-help-needed/#findComment-494545 Share on other sites More sharing options...
AP81 Posted March 18, 2008 Author Share Posted March 18, 2008 Spot on. Thanks! Link to comment https://forums.phpfreaks.com/topic/96636-recursive-function-help-needed/#findComment-494550 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.