openrat-cms

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

ArrayUtils.class.php (1675B)


      1 <?php
      2 
      3 namespace util;
      4 /**
      5  * Created by PhpStorm.
      6  * User: dankert
      7  * Date: 22.12.18
      8  * Time: 21:36
      9  */
     10 class ArrayUtils
     11 {
     12 
     13 	public static function getSubArray($array, $keys)
     14 	{
     15 
     16 		$a = $array;
     17 		foreach ($keys as $k) {
     18 			if (!isset($a[$k]))
     19 				return array();
     20 
     21 			if (!is_array($a[$k]))
     22 				return array();
     23 
     24 			$a = $a[$k];
     25 		}
     26 
     27 		return $a;
     28 	}
     29 
     30 
     31 	/**
     32 	 * Dives into an array and gets a value with a sub key.
     33 	 * @param array $array
     34 	 * @param array $keys
     35 	 * @return mixed|null
     36 	 */
     37 	public static function getSubValue($array, $keys)
     38 	{
     39 
     40 		$a = $array;
     41 		foreach ($keys as $k) {
     42 			if (!isset($a[$k]))
     43 				return null;
     44 
     45 			$a = $a[$k];
     46 		}
     47 
     48 		return $a;
     49 	}
     50 
     51 
     52 	/**
     53 	 * Maps an array to a new array.
     54 	 * @param $callback callable callback, it is called with 3 parameters: the new array, key, value.
     55 	 * @param $array array array which should be mapped
     56 	 * @return array the new array
     57 	 */
     58 	public static function mapToNewArray($array, $callback) {
     59 		$newArray = [];
     60 		foreach( $array as $key => $value ) {
     61 			$newArray += (array) call_user_func( $callback, $key, $value );
     62 		}
     63 		return $newArray;
     64 	}
     65 
     66 
     67 
     68 	/**
     69 	 * Make a dry flat array.
     70 	 *
     71 	 * @param $arr
     72 	 * @param $padChar
     73 	 * @param int $depth
     74 	 * @return array
     75 	 */
     76 	public static function dryFlattenArray($arr, $padChar = '  ', $depth = 0)
     77 	{
     78 		$new = array();
     79 
     80 		foreach ($arr as $key => $val) {
     81 			if (is_array($val)) {
     82 				$new[] = [
     83 					'key'  => str_repeat($padChar, $depth).$key,
     84 					'value'=> ''
     85 				];
     86 				$new = array_merge($new,self::dryFlattenArray($val, $padChar, $depth + 1));
     87 			} else
     88 				$new[] = [
     89 					'key'  => str_repeat($padChar, $depth).$key,
     90 					'value'=> $val
     91 				];
     92 		}
     93 		return $new;
     94 	}
     95 }