Language: php (GeSHi-highlighted)<?php function recurse($func, $args, $keys = true) { if (is_string($args[0])) { return call_user_func_array($func, $args); } else if (is_array($args[0])) { $data = $args[0]; unset($args[0]); $new_data = array(); foreach ($data as $key => $value) { if ($keys) { $key = call_user_func_array($func, array($key, $args)); } $new_data[$key] = (is_string($value)) ? call_user_func_array($func, array($value, $args)) : recurse($func, array(array($key => $value), $args)); } return $new_data; } } function test($data, $pad = false) { $data = strtoupper($data); if ($pad) { $data = '___' . $data . '___'; } return $data; } $array = 'mmm';//$array = array('bbb', 'ccc', array('ddd', 'eee' => 'ddd', array('fff')));echo test('aaa', true);$array = recurse('test', array($array, true));print_r($array); ?>
Language: php (GeSHi-highlighted)<?php function transform($data, $func, $args, $process_keys_flag = true) { if (is_string($data)) { // String => apply function on string return call_user_func_array($func, array_merge(array($data), $args)); } else if (is_array($data)) { // Array => apply transform on keys and values $new_data = array(); foreach ($data as $key => $value) { $new_value = transform($value, $func, $args, $process_keys_flag); if (is_string($key) && $process_keys_flag) { $new_key = transform($key, $func, $args); $new_data[$new_key] = $new_value; } else { $new_data[] = $new_value; } } return $new_data; } } function test($data, $pad = false, $pad2 = false) { $data = strtoupper($data); if ($pad) { $data = '___' . $data . '___'; } if ($pad2) { $data = 'xxx' . $data . 'xxx'; } return $data; } $array = array('bbb', 'ccc', array('ddd', 'eee' => 'ddd', array('fff'))); echo "<pre>before transform: ";print_r($array);echo "</pre>"; $array2 = transform($array, 'test', array(true, true));echo "<pre>after transform (true, true): ";print_r($array2);echo "</pre>"; $array3 = transform($array, 'test', array(true, false));echo "<pre>after transform (true, false): ";print_r($array3);echo "</pre>"; $array4 = transform($array, 'test', array(false, true));echo "<pre>after transform (false, true): ";print_r($array4);echo "</pre>"; ?>
Language: php (GeSHi-highlighted)<pre><?php function recurse($func, $args, $keys) { if (is_string($args[0])) { return call_user_func_array($func, $args); } else if (is_array($args[0])) { $data = $args[0]; $new_data = array(); foreach ($data as $key => $value) { if ($keys) { $args[0] = $key; $key = call_user_func_array($func, $args); } $args[0] = $value; $new_data[$key] = recurse($func, $args, $keys); } return $new_data; } } function test($data, $pad, $pad2) { $data = strtoupper($data); if ($pad) { $data = '___' . $data . '___'; } if ($pad2) { $data = 'xxx' . $data . 'xxx'; } return $data; } $array = 'mmm'; $array = array('bbb', 'ccc', array('ddd', 'eee' => 'ddd', array('fff'))); $array = recurse('test', array($array, true, true), true); print_r($array); ?></pre>