summaryrefslogblamecommitdiffstats
path: root/inc/arrayutil.inc.php
blob: 9d2dcfae0b77532b85aaaab917b80099d4295d5e (plain) (tree)
1
2
3
4
5
6
7
8
9
10
11
12











                                                                                 
                                                                     
         
                                                 

         




















                                                                                                  











                                                                                                         

















                                                                                         












                                                                                      
 
<?php

class ArrayUtil
{

	/**
	 * Take an array of arrays, take given key from each sub-array and return
	 * new array with just those corresponding values.
	 * @param array $list
	 * @param string $key
	 * @return array
	 */
	public static function flattenByKey(array $list, string $key)
	{
		return array_column($list, $key);
	}

	/**
	 * Pass an array of arrays you want to merge. The keys of the outer array will become
	 * the inner keys of the resulting array, and vice versa.
	 * @param array $arrays
	 * @return array
	 */
	public static function mergeByKey(array $arrays)
	{
		$empty = array_combine(array_keys($arrays), array_fill(0, count($arrays), false));
		$out = [];
		foreach ($arrays as $subkey => $array) {
			foreach ($array as $key => $item) {
				if (!isset($out[$key])) {
					$out[$key] = $empty;
				}
				$out[$key][$subkey] = $item;
			}
		}
		return $out;
	}

	/**
	 * Sort array by given column.
	 * @param array $array
	 * @param string $column
	 * @return void
	 */
	public static function sortByColumn(array &$array, string $column, int $sortFlags = SORT_REGULAR)
	{
		$sorter = array_column($array, $column);
		array_multisort($sorter, $sortFlags, $array);
	}

	/**
	 * Check whether $array contains all keys given in $keyList
	 *
	 * @param array $array An array
	 * @param array $keyList A list of strings which must all be valid keys in $array
	 * @return boolean
	 */
	public static function hasAllKeys(array $array, array $keyList): bool
	{
		if (!is_array($array))
			return false;
		foreach ($keyList as $key) {
			if (!isset($array[$key]))
				return false;
		}
		return true;
	}

	/**
	 * Check if all elements in given array are primitive types,
	 * i.e. not object, array or resource.
	 */
	public static function isOnlyPrimitiveTypes(array $array): bool
	{
		foreach ($array as $item) {
			if (is_array($item) || is_object($item) || is_resource($item))
				return false;
		}
		return true;
	}

}