Last active
August 29, 2015 14:20
-
-
Save jwerder/c21eb1deec92e3abb86f to your computer and use it in GitHub Desktop.
Format array using callback method
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| /** | |
| * Formatter of Array | |
| * @author Jimmy Werder <jimmy.werder@gmail.com> | |
| * @version 0.1 | |
| */ | |
| class ArrayFormatter | |
| { | |
| const KEY = 1; | |
| const VALUE = 2; | |
| /** | |
| * @static | |
| * @access public | |
| * @param array $array Array | |
| * @param callable $funcName Static Method Callback Ex: "MyClass::myCallbackMethod" | |
| * @param mixed $funcParam [optional] Parameter of Method Callback. Default empty array | |
| * @param int $walkInto [optional] Choice to change array keys or values. Default Keys | |
| * @return array Formatted Array | |
| * @author Jimmy Werder <jimmy.werder@gmail.com> | |
| * @since 2015-04-28 | |
| * @version 0.1 | |
| * @throws Exception In case to param $change invalid. | |
| */ | |
| public static function formatRecursive( array $array, callable $funcName, array $funcParam = array(), $walkInto = self::KEY ) | |
| { | |
| $arrayFormatted = array(); | |
| foreach ( $array as $k => $v ) { | |
| switch ( $walkInto ) { | |
| case self::KEY: | |
| $funcParam[0] = $k; | |
| $formattedKey = call_user_func_array( $funcName, $funcParam ); | |
| if ( is_array( $v ) ) | |
| $arrayFormatted[$formattedKey] = self::formatRecursive( $v, $funcName, $funcParam, $walkInto ); | |
| else | |
| $arrayFormatted[$formattedKey] = $v; | |
| break; | |
| case self::VALUE: | |
| if ( is_array( $v ) ) { | |
| $arrayFormatted[$k] = self::formatRecursive( $v, $funcName, $funcParam, $walkInto ); | |
| } else { | |
| $funcParam[0] = $v; | |
| $formattedValue = call_user_func_array( $funcName, $funcParam ); | |
| $arrayFormatted[$k] = $formattedValue; | |
| } | |
| break; | |
| default: | |
| throw new \Exception( 'Invalid value in param "$walkTo" in ' . __CLASS__ ); | |
| } | |
| } | |
| return $arrayFormatted; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment